Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring bean not autowiring with @Component annotation

Not sure what I'm doing wrong, but I have a webapp configuration that works in Unit Testing but dies in production for a Component bean.

The bean extends WebServiceGatewaySupport and extends an Interface.

I define it in java thusly:

@Component("myShippingImplementation")
public class MyShippingImplemenation extends WebServiceGatewaySupport implements ShippingImplementation {
    private String addressValidationUri;

    public String getAddressValidationUri() {
        return addressValidationUri;
    }

    public void setAddressValidationUri(String addressValidationUri) {
        this.addressValidationUri = addressValidationUri;
    }   
}

and the XML bean configuration is:

<bean id="myShippingImplementation" class="com.cerp.service.shipping.MyShippingImplemenation" autowire="byType">
    <property name="addressValidationUri" value="https://www.testurl.com" />
    <property name="defaultUri"           value="https://www.alturl.com" />
    <property name="marshaller" ref="marshaller"/>
    <property name="unmarshaller" ref="marshaller"/>
</bean>

If I wire this in a Unit test it works:

public class MyServiceClientTest extends BaseWebServiceTest {
    @Autowired MyShippingImplemenation c;

(BaseWebServiceTest uses SpringJUnit4ClassRunner)

but if I wire it in a Controller and run it off Tomcat with the following:

@Controller
@RequestMapping(value="/work/settings")
public class SettingsController {
    @Autowired
    SignupServiceI signupService;

    @Autowired
    ShippingImplementation myShipImplementation;

it dies. The problem is that the fields I defined in XML don't seem to be part of the bean that is autowired into the Controller. For example, I put a breakpoint in the setAddressValidationUri and I can see that it is called on application startup with the proper property. However, after the autowiring in the controller the instance of the bean has null for these values.

You will also notice that there's a SignupServiceI reference... this is a Service bean that does autowire successfully. It's an interface implemented by a class that is annotated with the @Service tag.

like image 882
IcedDante Avatar asked May 13 '14 05:05

IcedDante


1 Answers

Remove the @Component.

The adding of this annotation combined with component-scanning leads to two instances of the same bean (actually in your case one bean overrides the other, due to the same bean name/id). You have also defined it in XML. The one in XML is the one you want to use.

like image 110
M. Deinum Avatar answered Oct 26 '22 14:10

M. Deinum