spring中配置bean的方式有三种:
1>通过工厂方法
2>通过factoryBean方法配置
3>通过注解的方式配置
由于在开发中注解的方式使用得最多,因此,这里仅仅介绍注解的方式。
spring可以自动扫描classpath下特定注解的组件,组件包括:
@Component:基本组件,标识一个受spring管理的组件,可以应用于任何层次
@Repository:标识持久层组件,表示数据库访问
@Service:标识业务层组件
@Controller:标识控制层组件
对于扫描到的组件,spring有默认的命名规则,即类名的首字母小写;当然也可以在注解中通过使用value属性值标识组件的名称。
举例,如下两种形式是一样的
//1.注解方式配置bean

@Service
public class Address {
	private String city;
	private String street;
}

//2.xml方式配置bean

<bean id="address" class="com.test.autowired.Address">
	</bean>

当在工程中的某些类上使用了注解后,需要在spring的配置文件中声明context:component-scan:
1>base-package:指定一个需要扫描的基类包,spring容器会扫描这个基类包及其所有的子包里面的所有类。
2>当需要扫描多个包时,可以使用逗号分隔。
3>如果仅仅希望扫描指定包下面部分的类,而不是所有的类,可以使用resource-pattern属性过滤特定的类。
示例1:扫描com.test.annotation和com.test.autowired两个包及其子包下面所有的class
xml文件如下

<!-- 扫描com.test.annotation包和com.test.autowired包及其子包所有的类   -->
	<context:component-scan base-package="com.test.annotation,com.test.autowired">
	</context:component-scan>

示例2:扫描com.test.annotation包下子包repository下所有的类
xml配置文件如下

<!-- 扫描com.test.annotation包下子包repository下所有的类 -->
	<context:component-scan base-package="com.test.annotation"
	resource-pattern="repository/*.class">
	</context:component-scan>

示例3:不包含某些子节点(方式一:按照注解来包含与排除)

<!-- 扫描com.test.annotation包下所有的类,排除@Repository注解(其他注解类似) -->
	<context:component-scan base-package="com.test.annotation">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
	</context:component-scan>

示例4:只包含某些子节点(方式一:按照注解来包含与排除)

<!-- 扫描com.test.annotation包下所有的类,只包含@Repository注解(其他注解类似) -->
	<!-- 注意:此时需要设置use-default-filters="false",false表示按照下面的过滤器来执行;true表示按照默认的过滤器来执行 -->
	<context:component-scan base-package="com.test.annotation" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
	</context:component-scan>

示例5:不包含某些子节点(方式二:按照类名/接口名来包含与排除)

<!-- 扫描com.test.annotation包下所有的类,不包含UserService接口及其所有实现类 -->
	<context:component-scan base-package="com.test.annotation">
		<context:exclude-filter type="assignable" expression="com.test.annotation.service.UserService"/>
	</context:component-scan>

示例6:只包含某些子节点(方式二:按照类名/接口名来包含与排除)

<!-- 扫描com.test.annotation包下所有的类,只包含UserRepository接口及其所有实现类 -->
	<context:component-scan base-package="com.test.annotation" use-default-filters="false">
		<context:include-filter type="assignable" expression="com.test.annotation.repository.UserRepository"/>
	</context:component-scan>