How to autowire bean in same bean

2019-02-20 09:53发布

I would like to autowire instance of bean A to the same instance of A. How can I achieve this with annotation (without XML).

Example:

@Service
public class A {

    @Autowire
    A a;

}

I also tried

@Service
public class A {

    A a;

    @Autowired
    public void setA(final A a) {
        this.a = a;
    }

}

but it is not working too :-/

Configuration using XML like

<bean id="a" class="A">
    <property name="a" ref="a" />
</bean>

works fine. And also it's possible to use

@Service
public class A implements InitializingBean {

    A a;

    @Autowired
    ApplicationContext ctx;

    @Override
    public void afterPropertiesSet() throws Exception {
        a = ctx.getBean(A.class);
    }

}

but this is cumbersome. The strange thing is, that Spring can handle this when using XML configuration, but not when using annotation-based one.

3条回答
Melony?
2楼-- · 2019-02-20 10:15

You can use compile-time weaving (with Aspectj compiler) so aspects do not need proxy to work. Just add this into your pom.xml configuration:

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
</dependency>

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <configuration>
        <aspectLibraries>
            <aspectLibrary>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
            </aspectLibrary>
        </aspectLibraries>
    </configuration>
</plugin>
查看更多
干净又极端
3楼-- · 2019-02-20 10:35

@Autowired skip the annotated bean when looking for autowire candidates, use @Resource instead.

查看更多
别忘想泡老子
4楼-- · 2019-02-20 10:36

Do I understand it right, and is your root problem the fact that your Transactional advice is not applied because you call a transactional method from within a non-transactional method in the same class? Can't you just extract the transactional code into another class? Isn't that more readable than this imho really weird construct?

Eg.

@Service
public class A {

  @Autowired B b;

  void doSomething() {
     b.m();  
  }
}

public class B {

   @Transactional
   void m() { .. }
}
查看更多
登录 后发表回答