【问题标题】:Converting spring xml to java configuration with implicit setter autowiring and ComponentScan使用隐式设置器自动装配和 ComponentScan 将 spring xml 转换为 java 配置
【发布时间】: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


    【解决方案1】:

    在 sprig java 配置中没有等效于 default-autowire="byName" 全局 xml 标记属性。

    更多,注入的正确方法是使用 cdi 的 @Inject 注释或 spring 的 @Autowired 注释。所以,应该修改 Car 类:

    package vehicle;
    
    @Named
    public class Car {
    
      @Inject
      private Tire tire;
    
      public Tire getTire() {
        return this.tire;
      }
    }
    

    现在,xml 或 java 配置都可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-30
      • 2011-01-15
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多