我有两个班:vehicle.Tire和vehicle.Car。
package vehicle;
@Named
public class Tire {
private String age;
}
package vehicle;
@Named
public class Car {
private Tire tire;
// Spring calls this setter because default-autowire="byName" of xml configuration
public void setTire(Tire newTire) {
this.tire = newTire;
}
public Tire getTire() {
return this.tire;
}
}
以下spring xml工作正常。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
default-autowire="byName">
<context:component-scan base-package="vehicle" />
</beans>
我尝试在上面创建一个java配置:
@Configuration
@ComponentScan(basePackages={"vehicle"})
public VehicleConfig {
}
我不在类中使用@Inject或@Autowired注释,但是spring autowires 并且它适用于xml。 使用java配置,不会调用Car的方法setTire :(
缺少什么?如何更改java配置使用组件扫描而不修改Car and Tire类?是否 default-autowire =“byName” xml标记属性在java中等效?
我使用上面的类来测试java配置
@Test
public class VehicleConfigTest {
public void testTire() {
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext();
applicationContext.register(VehicleConfig.class);
applicationContext.refresh();
Car car = applicationContext.getBean(Car.class);
Assert.assertNotNull(car.getTire());
}
}
提前致谢。