Spring 能够从 classpath 下自动扫描、侦测和实例化具有特定注解的组件。
特定注解有(放在类上面的):
@Controller:标识表现层组件
@Service:标识服务层组件
@Respository:标识持久层组件
@Component:基本注解,标识了一个受Spring管理的组件
对于扫描到的组件,Spring有默认的命名策略,使用非限定类名,第一个字母小写,也可以在注解中通过value属性值标识组件的名称。
当组件类上使用了特定的注解之后,还需要在Spring的配置文件中声明<contest:component-scan>标签。
它的属性有:
1、base-package:指定一个需要扫描的基类包,Spring容器将会扫描这个基类包里极其子包中的所有类,当需要扫描多个包时,可以使用逗号分隔。
2、resource-pattern:指定扫描的类,如:
<context:component-scan base-package="com.qw" resource-pattern="spring/*.class"/>
只扫描com.qw下面的spring子包所有的类,com.qw下面及其他子包的类不扫描。
3、use-default-filters:默认为true,所有的注解,如果是false,则要扫描那些注解,就需要自己来配置了。
<contest:component-scan>子标签(可以拥有若干个子标签):
1、<context:include-filter type="annotation"/>:需要扫描那些注解,属性:expression
例子如下:
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
它是可以扫描到@Controller注解的,这个地方用它,需要和use-default-filters属性一起用,才可以。
2、<context:exclude-filter type="annotation"/>:不需要扫描到那些注解,属性:expression
例子如下:
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component"/>
它是不可以扫描到@Controller注解的。
Spring还有可以解决bean和bean之间关联关系的注解。
@Autowired
@Resource
@Inject
如:
@Component
public class HelloWorld {
@Autowired//这个注解就是解决这两个bean的关联关系的。
private Car car;
public void hello(){
car.carhe();
System.out.println("hello:");
}
}
@Component
public class Car {
public void carhe(){
System.out.println("我是车");
}
}
Spring IOC容器的注解配置Bean的全部配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd ">
<!-- 扫描com.qw.spring包及其子包下面的所有的类的注解 -->
<context:component-scan base-package="com.qw.spring"/>
</beans>