使用隐式设置器自动装配和ComponentScan将Spring xml转换为Java配置 [英] Converting spring xml to java configuration with implicit setter autowiring and ComponentScan
问题描述
我有两个班级:Vehicle.Tire和vehicle.Car.
I have two classes: vehicle.Tire and 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可以正常工作.
The following spring xml works fine.
<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配置:
I tried to create a java configuration above:
@Configuration
@ComponentScan(basePackages={"vehicle"})
public VehicleConfig {
}
我不在类中使用@Inject或@Autowired注释,但是使用 autowires ,它可以与xml一起使用. 使用java配置,Car的setTire方法不称为:(
I'm not using @Inject nor @Autowired annotations in the classes, but spring autowires and it works with xml. Using java configuration, the method setTire of Car is not called :(
缺少什么?我如何使用组件扫描更改而无需修改汽车和轮胎类? Java中是否有 default-autowire ="byName" xml标记属性等效项?
What is missing? How can I change java configuration using component scan without modifying Car and Tire classes? Is there default-autowire="byName" xml tag attribute equivalent in java?
我使用上面的类来测试Java配置
I used the class above to test java configuration
@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());
}
}
谢谢.
推荐答案
在小枝Java配置中,没有等效于default-autowire ="byName"全局xml标签属性的
There is no equivalent in sprig java configuration to default-autowire="byName" global xml tag attribute.
更多,正确的注入方式是使用cdi的@Inject注释或spring的@Autowired注释.因此,应该修改Car类:
More, the right way to have injection is using @Inject annotation by cdi or @Autowired annotation by spring. So, the class Car should be modified:
package vehicle;
@Named
public class Car {
@Inject
private Tire tire;
public Tire getTire() {
return this.tire;
}
}
现在,无论是xml还是java配置都可以使用.
Now, both xml or java configuration works.
这篇关于使用隐式设置器自动装配和ComponentScan将Spring xml转换为Java配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!