java - AutowireCapableBeanFactory.autowireBeanProperties() seems not to work for xml configured contexts -
i trying manually inject beans autowired dependency using autowirecapablebeanfactory.autowirebeanproperties(). seems work if bean should injected configured in java class. if configured in xml context file not work.
test cases:
public class injectortest { @test public void testannotationinjector() { annotationconfigapplicationcontext context = null; try { testbean testbean = new testbean(); context = new annotationconfigapplicationcontext(someserviceconfig.class);; autowirecapablebeanfactory beanfactory = context.getautowirecapablebeanfactory(); beanfactory.autowirebeanproperties(testbean, autowirecapablebeanfactory.autowire_by_type, false); asserttrue(testbean.getsomeservice() != null); } { if (context != null) { context.close(); } } } @test public void testxmlinjector() { classpathxmlapplicationcontext context = null; try { testbean testbean = new testbean(); context = new classpathxmlapplicationcontext("test-some-service-context.xml"); autowirecapablebeanfactory beanfactory = context.getautowirecapablebeanfactory(); beanfactory.autowirebeanproperties(testbean, autowirecapablebeanfactory.autowire_by_type, false); asserttrue(testbean.getsomeservice() != null); } { if (context != null) { context.close(); } } } private class testbean { @autowired private someservice someservice; public someservice getsomeservice() { return someservice; } }
the first test case runs successfully. second 1 fails. can explain behaviour?
here rest of code:
someservice.java
public class someservice { public void dosomething() { system.out.println("did something"); } }
java context configuration
@configuration public class someserviceconfig { @bean public someservice someservice() { return new someservice(); } }
test-some-service-context.xml
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean class="webapplication.injector.someservice"></bean> </beans>
the second test case fails because testbean
don't have setter someservice property , context don't register autowiredannotationbeanpostprocessor
so, fix add setter someservice or add <context:annotation-config/>
bean definition file.
Comments
Post a Comment