首页 > 编程语言 > 详细

【Spring】IOC样例

时间:2021-09-05 20:14:27      阅读:12      评论:0      收藏:0      [点我收藏+]

 

一、注解方式

@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样例

原文:https://www.cnblogs.com/clarino/p/15227393.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!