How to autowire bean in same bean

后端 未结 3 939
无人共我
无人共我 2021-01-23 04:52

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:



        
相关标签:
3条回答
  • 2021-01-23 05:07

    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>
    
    0 讨论(0)
  • 2021-01-23 05:08

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

    0 讨论(0)
  • 2021-01-23 05:24

    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() { .. }
    }
    
    0 讨论(0)
提交回复
热议问题