您的位置:首页 > 编程语言 > Java开发

Spring装配bean的三种方式

2017-02-27 10:03 363 查看
spring装配bean有显式和隐式两种:

         1.显式的配置:

                  1).通过javaConfig来配置(@Configuration和@Bean结合)

@Configuration
public class BeanConfig {

@Bean
public A a() {

return new A();
}

@Bean
public B b() {

B bb = new B();
bb.setA(a());
return bb;
}
}

                  2).通过xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用bean标签去申明bean-->
<bean id="waiter" class="xyz.mrwood.study.spring.example.Waiter" />
<!--可以保用p标签来注入依赖的bean-->
<bean id="store" class="xyz.mrwood.study.spring.example.Store" p:waiter-ref="waiter" />

</beans>

         2.隐式的配置:

                  1).通过扫描包,自动装配

java类(其中Configuration可以由Service和Controller代替):

@Configuration
@ComponentScan
public class ApplicationConfig {
}XML:
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="xyz.mrwood.study.spring.example" />

</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring