【Spring】IOC样例

 

一、注解方式

@Configuration

@ComponentScan("com.baeldung.constructordi"): perform a context scan for additional beans.

@Bean

 1 @Configuration
 2 @ComponentScan("com.baeldung.constructordi")
 3 public class Config {
 4 
 5     @Bean
 6     public Engine engine() {
 7         return new Engine("v8", 5);
 8     }
 9 
10     @Bean
11     public Transmission transmission() {
12         return new Transmission("sliding");
13     }
14 }

其他Bean定义,通过上述@ComponentScan扫描得到

1 @Component
2 public class Car {
3 
4     @Autowired
5     public Car(Engine engine, Transmission transmission) {
6         this.engine = engine;
7         this.transmission = transmission;
8     }
9 }

使用:AnnotationConfigApplicationContext

Spring will encounter our Car class while doing a package scan, and will initialize its instance by calling the @Autowired annotated constructor.

By calling the @Bean annotated methods of the Config class, we will obtain instances of Engine and Transmission. Finally, we need to bootstrap an ApplicationContext using our POJO configuration:

1 ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
2 Car car = context.getBean(Car.class);

 

二、XML配置

定义构造器的XML Bean配置

<bean id="toyota" class="com.baeldung.constructordi.domain.Car">
    <constructor-arg index="0" ref="engine"/>
    <constructor-arg index="1" ref="transmission"/>
</bean>

<bean id="engine" class="com.baeldung.constructordi.domain.Engine">
    <constructor-arg index="0" value="v4"/>
    <constructor-arg index="1" value="2"/>
</bean>

<bean id="transmission" class="com.baeldung.constructordi.domain.Transmission">
    <constructor-arg value="sliding"/>
</bean>

使用ClassPathXmlApplicationContext

1 ApplicationContext context = new ClassPathXmlApplicationContext("baeldung.xml");
2 Car car = context.getBean(Car.class);

 

【Spring】IOC样例

上一篇:Java-一维数组去重


下一篇:java数组:数组声明、创建、初始化以及数组角标越界