Spring学习总结之装配bean

1.  XML中显式配置

规范,文件头:

           <?xml version=”1.0” encoding=”UTF-8”?>

           <beans xmlns=http://www.springframework.org/schema/beans

                    xmlns=http://www.w3.org/2001/XMLSchema-instance

                    xsi:schemaLocation=”http://www.springframework.org/schema/beans

                             http://www.springframework.org/schema/beans/spring-beans.xsd

                             http://www.springframework,org/schema/context”>

          

                    <!—configuration details go here -->

           </beans>

1)  声明一个简单的bean

<bean id=”test” class=”com.song.Test” />

没有明确给定ID时,bean将根据全限定类名进行命名,“com.song.Test

#0”,其中#0只是一个技术形式,用来区分相同类型的其他bean

2)  构造器注入

<bean id=”test” class=”com.song.Test”>

            <constructor-arg ref=”hello” />

</bean>

此时,spring会将ID为hello的bean作为com.song.Test的构造方法的参数传入;如果是字面量(如字符串之类的常量),将ref修改为value

<bean id=”test” class=”com.song.Test”

            c:hello-ref=”hello” />

这是c-命名空间,其中c是标志,hello是com.song.Test的属性的属性名,ref是注入参数标志,”hello”表示注入的bean的ID;可以将hello替换为_0(_1,_2)表示第几个参数,与之对应;只有一个参数时,可以直接用_对hello替换;如果是字面量,去掉-ref;使用c-命名空间需要在文件头中加入:

            xmlns:c=”http://www.springframework.org/schema/c”

constructor-arg和c-命名空间区别主要是constructor-arg可以装配集合

3)  属性注入

使用属性的setter方法注入属性

<bean id=”test” class=”com.song.Test”>

            <property name=”hello” ref=”hello” />

</bean>

 name为属性名,ref为注入的bean的ID;如果注入的是字面量,将ref改为value

<bean id=”test” class=”com.song.Test”

            p:hello-ref=”hello” />

p-命名空间,hello是com.song.Test的属性的属性名,ref是注入参数的标志,”hello”表示注入的bean的ID;如果注入的是字面量,去掉-ref;使用p-命名空间需要在文件头中加入:

            xmlns:p=”http://www.springframework.org/schema/p”

property和p-命名空间区别主要是property可以装配集合

2.  Java中显式配置

@Configuration

public class HelloConfig {

            @Bean

            public Hello sayHello() {

                     return new HelloImpl();

            }

}

         @Bean注解同样可以添加名字,比如@Bean(name=“hello”),

         带@Bean注解的方法可以采用任何必要的Java功能来产生bean实例,比如在方法中加一些条件判断,返回不同的实例

3.  隐式的bean发现机制和自动装配

组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean

自动装配(autowiring):spring自动满足bean之间的依赖

1)  创建可被发现的bean

使用注解@Component(或@Named,只有细微差别,基本上可以互换),同时启用组件扫描,方式有:@Configuration@ComponentScan注解,XML配置(component-scan)

2)  为组件扫描的bean命名

@Component(“beanName”)或者@Named(“beanName”)

3)  设置组件扫描的基础包

@ComponentScan(“packageName”)或者@ComponentScan( basePackages = {“packageName1”, ”packageName2”…})

4)  通过注解实现自动装配

@Autowired@Inject在大多数情况下可以互换)

posted @ 2017-04-11 10:09  buaa小松  阅读(221)  评论(0编辑  收藏  举报