Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring injected resource is always null

ISSUE:

I am trying to inject a service into a bean but the service instance is always null.

BACKGROUND:

I have two beans one called from the other. This is how they are defined in XML config:

<context:annotation-config />
<bean class="com.test.MyBeanImpl" name="myBean"/>
<bean id="myService" class="com.test.MyServiceImpl" />

and the beans are implemented like so:

MyServiceImpl.java

class MyServiceImpl implements MyService {
    public void getString() {
        return "Hello World";
    }
} 

MyBeanImpl.java

@Component
class MyBeanImpl implements MyBean, SomeOtherBean1, SomeOtherBean2 {
    @Resource(name="myBean")
    private MyService myService;

    public MyBeanImpl() {}
}

QUESTIONS:

Is there some reason related to the fact that my bean implements 3 interfaces that is preventing the Service being injected? If not what other factors could be effecting it?

like image 224
travega Avatar asked Jan 15 '14 00:01

travega


People also ask

Why my Autowired Bean is null?

The field annotated @Autowired is null because Spring doesn't know about the copy of MileageFeeCalculator that you created with new and didn't know to autowire it.

Why is my Autowired not working?

When @Autowired doesn't work. There are several reasons @Autowired might not work. When a new instance is created not by Spring but by for example manually calling a constructor, the instance of the class will not be registered in the Spring context and thus not available for dependency injection.

What does @resource mean in Spring?

The @Resource annotation in spring performs the autowiring functionality. This annotation follows the autowire=byName semantics in the XML based configuration i.e. it takes the name attribute for the injection.


1 Answers

as you are using annotations Just mark your service class with @Service annotation and use @Autowired annotation to get the instance of your service class

MyServiceImpl.java

package com.mypackage.service;
@Service
class MyServiceImpl implements MyService {

    public void getString() {
        return "Hello World";
    }
} 

MyBeanImpl.java

@Component
class MyBeanImpl implements MyBean, SomeOtherBean1, SomeOtherBean2 {

    @Autowired  
    private MyService myService;

    public MyBeanImpl() {}
}

also make sure you mention your package name in <context:component-scan /> element in your dispatcher file as

<context:annotation-config />
<context:component-scan base-package="com.mypackage" />

hope this will solve your problem

like image 117
Ashish Jagtap Avatar answered Sep 21 '22 10:09

Ashish Jagtap