In my web spring application I create an instance with key word new
as following.
In my one of action class, following method exists.
public void process() {
MyBean b=new MyBean(); //initiated the instance with new
b.process();
}
Other MyBean class
@Service
public class MyBean {
@Autowired
MyService service;
public void process() {
service.execute(); // this service instance has not initialized by Spring DI :( .service object is null.
}
the MyService instance is not set by spring Dependency injection. Is it because that I create the instance of MyBean myself with new
not the Spring ?
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
onMybean
instance.Second is to use
@Configurable
onMyBean
class. With the@Configurable
annotation spring will inject dependencies even for objects created throughnew
keyword. Remember to haveAspectJ
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.xmlYou 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.
In your case, spring does not recognize
MyBean
bean because you are creating it withnew
operator. Let spring initialize this bean and then you can have autowired beans accessed insideMyBean
. For e.g.Above entry in your application context will create
MyBean
in spring container. And using this object you can access the services written inside it.When you create an object by new, autowire\inject don't work...
as workaround you can try this:
create your template bean of MyBean
and create an istance in this way
PROTOTYPE : This scopes a single bean definition to have any number of object instances.
If you want to autowire programmatically, you can use:
Another solution can be the use of
@Component
like this:And at your class where
process()
is, you can Autowire like this: