使用隐式setter自动连接将SpringXML转换为java配置

使用隐式setter自动连接将SpringXML转换为java配置,spring,autowired,spring-java-config,Spring,Autowired,Spring Java Config,我想将SpringXML转换为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/bea

我想将SpringXML转换为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>
我不是在使用@Inject或@Autowired注释,而是在使用springAutowired,它可以工作。 如何在不修改汽车和轮胎类的情况下将xml更改为java配置


提前感谢。

这是psuedo/示例代码(可能有语法错误)

下面是如何访问上下文:

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

参考:

这主要是对萨尔曼答案的修正

您确实可以使用一个配置类来实现您的需求,但是您必须
car
bean中注入
tire
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.java
Tire.java
未被触动(那里没有注释),并且仍然可以在
Car
bean中注入
Tire
bean。

这里,Car()方法要求将轮胎作为参数。当春天 调用car()来创建carbean,它会自动将轮胎连接到 配置方法。然后,方法主体可以在其认为合适的情况下使用它。有了这种技术,car()方法仍然可以将轮胎注射到轮胎中 Car setTire方法,无需显式引用轮胎@Bean 方法


}

这是错误的:
@Bean
注释不够神奇,无法破坏编码。您可以明确地编写
car.setTire(tire())
。由于轮胎在每次调用时都返回一个新轮胎,因此您在
car
bean中注入的轮胎不是
tire
bean。您可能需要查找spring概念。如果谢尔盖的答案更符合你的要求,你可以使用它。谢谢你的回答,@Salman。事实上,我的具体问题是:谢谢你的回答,@ricardo。事实上,我的具体问题是:
public static void main(String[] args) {
   ApplicationContext ctx = 
   new AnnotationConfigApplicationContext(MyAppConfig.class);
   Car car = ctx.getBean(Car.class);
}
@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();
    }
}
@Configuration
public class MyAppConfig {

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