spring能够从classpath下自动扫描,侦测和实例化具有特定注解的组件。
可以将带有注解的类,注入到IOC容器当中,这些类受IOC容器管理
<?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">
<!-- 自动扫描指定包以及子包下所有添加了注解的类,然后加入到IOC容器当中-->
<context:component-scan base-package="spring"></context:component-scan>
</beans>
可以设置只扫描特定的类:
<!-- 设置只扫描时,需更改扫描规则use-default-filters="false"-->
<context:component-scan base-package="spring" use-default-filters="false">
<!-- 只扫描特定注解的类-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<!-- 只扫描自己写的某个类-->
<context:include-filter type="assignable" expression="spring.controller.UserController"/>
</context:component-scan>
可以设置扫描时排除的类
<context:component-scan base-package="spring">
<!-- 只排除特定注解的类-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<!-- 只排除自己写的某个类-->
<context:exclude-filter type="assignable" expression="spring.controller.UserController"/>
</context:component-scan>
特定组件包括:
- @Component:基本注解,标识了一个受spring管理的组件
- @Repository:标识持久层组件
- @Service:标识服务层(业务层)组件
- @Controller:标识表现层组件
- @Autowired:自动注入,会将IOC容器中的对象自动注入给我们要使用的对象当中。注意,使用这个注解的前提是,要被注入的那个对象所在的类要受IOC容器管理。
使用getBean获取类对象的方法是让类名第一个字母小写,等价于< bean>中的id属性