一.Spring的注解:
@Component是一个通用的注解,可用于任何一个bean;
@Repository通常用来注解dao类,即持久层(数据层);
@Service通常用来注解service类,即服务层;
@Controller通常用来注解controller类,即控制层(mvc);
二.Spring具有自动检测并注册注解的机制,使用方法如下:
@Service/@Controller/@Repository
public class example{
}(注:方法和参数也可以注解)
三.xml配置:
(只会查找同一个Applicatcontext中bean的注解,一般不用,用下面的)
(扫描这个包下的所有bean)
四.通过过滤器进行自定义扫描:
默认情况下,只要类有@Component/@Repository/@Controller/@Service就会被自动注册bean.但是我们可以通过下面的配置修改这种行为:
<context:component-scan base-package="org.example">
<context:include-filter type="regex"
expression=".*Stub.*Repository"/>
<context:exclude-filter type="annotation"
experssion="org.springfor*.*.Repository"/>
</context:component-scan>(type的种类有很多:自行google filter)
五.定义bean:
@Service("myMovielister")(显示指定bean的id)
public class SimpleMovieLister{}
(注:当没有显示指定时,默认id是首字母小写的类名)
我们也通过如下配置自定义命名方式实现BeanNameGenerator:
<context:component-scan base-package="org.exmaple" name-generator="org.exampel.MyNameGenerator"/>(MyNameGenerator接口一定要有个无参的构造器)
六.作用域:
@Scope("prototype")
@Repository
public class example{}
也可以自定义scope策略,实现带有无参构造器的,MyScopeResolver接口:
<context:component-scan base-packege="org.example" scope-resolver="org.example.MyScopeResolver"/>
七.代理: 使用scope-proxy属性指定代理(与上相同),有三个值:no,interface,targetClass,默认是no
(注:指定代理是请求方向ioc请求对象,ioc生存实例给请求方后就让实例自生自灭,所以需要指定代理来管理它)
<context:component-scan base-packege="org.example" scope-proxy="org.example.MyScopeproxy"/>