spring注解方式实现IOC
@Component:
放在类上,用于标记告诉spring当前类需要有容器实例化bean并放入容器中
该注解有三个子注解:
@Controller:用于实例化controller层bean
@Service:用于实例化service层bean
@Repository:用于实例化持久层bean
注意:当不知道是哪一层的时候建议Component
添加注解扫描,扫描指定的包,将包中的所有注解的类实例化
base-package:后面放要扫描的包,如果有很多要扫描的,可以用逗号隔开或者可以直接写上一层的路径
<!--扫描-->
<context:component-scan base-package="com.msb.bean"></context:component-scan>
可以通过注解指定bean的id,如果不指定的话,则默认是类名且首字母小写
如下代码所示:
//@Component("user1")
@Component
public class User {
}
可以添加属性选择性扫描或者不扫描含有某一个注解的类
use-default-filters="true"默认的扫描过滤器包含@Component @Coontroller @Service @Repository四个注解
include-filter :控制只扫描哪些IOC注解
exclude-filter:控制不扫描哪些IOC注解
<context:component-scan base-package="com.msb.bean" use-default-filters="true">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>