使用隐式setter自动装配将spring xml转换为java配置

时间:2015-07-02 17:17:28

标签: spring autowired spring-java-config

我想将spring xml转换为java配置。

<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-4.1.xsd
   default-autowire="byName">

  <bean name="car" type="Car" />
  <bean name="tire" type="Tire" />

</beans>

我有两个班:汽车和轮胎。

public class Tire {
    private String age;
}

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;
    }
}

使用@Inject或@Autowired注释,但是春天自动装配并且它有效。 如何在没有修改Car and Tire类的情况下将xml更改为java配置

提前致谢。

3 个答案:

答案 0 :(得分:0)

这是伪造的/示例代码(可能有语法错误)。

import org.springframework.context.annotation.*;
import Car;
import Tire;

@Configuration
public class MyAppConfig {
  @Bean 
  public Car car() {
    Car car =new Car();
    car.setTire(tire());
    return car;
  }
  @Bean
  public Tire tire() {
    return new Tire();
  }
}

以下是访问上下文的方法:

public static void main(String[] args) {
   ApplicationContext ctx = 
   new AnnotationConfigApplicationContext(MyAppConfig.class);
   Car car = ctx.getBean(Car.class);
}

参考:spring_java_based_configuration

答案 1 :(得分:0)

这主要是对萨尔曼回答的解决方法。

您确实可以使用配置类来满足您的要求,但必须tire bean中注入car bean而不是任意Tire。您可以使用以下事实:配置类合法地将自己的bean注入其中:

@Configuration
public class MyAppConfig {
    @Autowired
    Tire tire;

    @Bean 
    public Car car() {
        Car car =new Car();
        car.setTire(tire);
        return car;
    }
    @Bean
    public Tire tire() {
        return new Tire();
    }
}

这样,您可以保持Car.javaTire.java不受影响(没有注释),并且仍然在tire bean中注入car bean。

答案 2 :(得分:0)

这里,car()方法要求轮胎作为参数。当春天 调用car()来创建Car bean,它将一个Tire自动装入 配置方法。然后该方法的主体可以使用它,但它认为合适。使用这种技术,car()方法仍然可以将Tire注入 Car setTire方法没有明确引用Tire @Bean 方法

foo
./test: symbol lookup error: ./libfoo.so: undefined symbol: bar

}