Converting spring xml to java configuration with implicit setter autowiring and ComponentScan

南楼画角 提交于 2020-01-13 07:05:31

问题


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

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>

I tried to create a java configuration above:

@Configuration
@ComponentScan(basePackages={"vehicle"})
public VehicleConfig {
}

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 :(

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?

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

}

Thanks in advance.


回答1:


There is no equivalent in sprig java configuration to default-autowire="byName" global xml tag attribute.

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

Now, both xml or java configuration works.



来源:https://stackoverflow.com/questions/31192940/converting-spring-xml-to-java-configuration-with-implicit-setter-autowiring-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!