【发布时间】:2015-09-20 11:26:42
【问题描述】:
我有两个类: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方法:(
缺少什么?如何使用组件扫描不修改 Car 和 Tire 类来更改 java 配置? java中是否有default-autowire="byName" xml标记属性等效?
我用上面的类来测试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());
}
}
提前致谢。
【问题讨论】:
标签: spring autowired inject spring-java-config