Binding with @Autowired not working inside instances initiated with 'new'

前端 未结 5 1058
谎友^
谎友^ 2021-01-20 08:04

In my web spring application I create an instance with key word new as following.
In my one of action class, following method exists.

publi         


        
5条回答
  •  没有蜡笔的小新
    2021-01-20 08:25

    Yes. It is not being set by DI of Spring as the instance you created using new keyword is not being managed by Spring container. Spring will by default inject dependencies only for spring managed instances. So to resolve this problem you can do it by two ways. First is don't use the new and use @Autowired on Mybean instance.

    Second is to use @Configurable on MyBean class. With the @Configurable annotation spring will inject dependencies even for objects created through new keyword. Remember to have AspectJ jars on your classpath with @configurable annotation as Spring need them to inject Dependecies.

    For the second approach use @Configurable(preConstruction = true) and add the following dependencies to your pom.xml

    org.springframework
    spring-aspects
    3.1.1.RELEASE
    
    org.aspectj
    aspectjrt
    1.6.8
    
    
    org.aspectj
    aspectjweaver
    1.6.8
    
    
    org.aspectj
    aspectjtools
    1.6.8
    
    

    You also need to compile it through AspectJ Compiler so that Byte code generated has the required abilities. You should use the following entries to make sure system using AspectJ Compiler at compile time.

    
    
    
    org.codehaus.mojo
    aspectj-maven-plugin
    1.4
    
    true
    1.6
    1.6
    ignore
    1.6
    UTF-8
    false
    
    
    org.springframework
    spring-aspects
    
    
    
    
    
    
    compile
    test-compile
    
    
    
    
    
    org.aspectj
    aspectjrt
    1.6.8
    
    
    org.aspectj
    aspectjtools
    1.6.11
    
    
    
    
    
    

提交回复
热议问题