Spring基于注解管理bean
和 XML 配置文件一样,注解本身并不能执行,注解本身仅仅只是做一个标记,具体的功能是框架检测到注解标记的位置,然后针对这个位置按照注解标记的功能来执行具体操作。
本质上:所有的一切操作都是由Java代码完成的,XML和注解只是告诉框架中的Java代码如何执行
注解
@Component:将类标识为普通组件
@Controller:将类标识为控制层组件
@Service:将类标识为业务层组件
@Repository:将类标识为持久层组件
注:通过查看源码我们得知,@Controller、@Service、@Repository这三个注解只是在@Component注解
的基础上起了三个新的名字,让我们能够便于分辨组件的作用。
扫描
Spring 为了知道程序员在哪些地方标记了什么注解,就需要通过扫描的方式,来进行检测。然后根据注解进行后续操作
使用注解的方式需要在配置文件中配置扫描,通过注解+扫描所配置的bean的id,默认值为类的小驼峰,即类名的首字母为小写的结果(可以通过标识组件注解的value属性值自定义id)
以下为具体的代码实现:
@Controller
public class UserController {
}
public interface UserService {
}
@Service
public class UserServiceImpl implements UserService {
}
public interface UserDao {
}
@Repository
public class UserDaoImpl implements UserDao {
}
这里需要特别注意,context:exclude-filter标签里的type属性可以设置排除扫描的类型,使用的比较多的就是:(annotation:根据注解类型进行排除),以后在整合Spring MVC中就会用到。至于包含扫描十分鸡肋了解即可
<?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 https://www.springframework.org/schema/context/spring-context.xsd">
<!--
1.context:exclude-filter:排除扫描
type:设置排除扫描的方式
type=“annotation|assignable”
annotation:根据注解类型进行排除,expression中需要设置排除注解的全类名
assignable:根据类的类型进行排除,expression中需要设置排除的类的全类名
2.context:include-filter:包含扫描(实际中意义不大)
注意:需要在context:component-scan标签中设置use-default-filters="false"
use-default-filters="true"(默认),所设置的包下所有的类都需要扫描,此时可以使用排除扫描
use-default-filters="false",所设置的包下所有的类都不需要扫描,此时才可以使用包含扫描
-->
<!--扫描组件-->
<context:component-scan base-package="com.qcw.spring"></context:component-scan>
// <context:component-scan base-package="com.qcw.spring" use-default-filters="false">-->
// <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
//<!– <context:exclude-filter type="assignable" expression="com.qcw.spring.controller.UserController"/>–>-->
//<!– <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>–>-->
// </context:component-scan>-->
</beans>