通过给bean上面加上某些注解,可以快速地将bean注入到IOC容器中
spring有四个注解
@Controller:控制器层
@Service:业务逻辑层
@component:通用
@Repository:持久层
这些注解都能将bean注入IOC容器,可以顺便选一个使用,
但是推荐按照上面写的加注解,方便别的程序员理解程序
使用注解将bean注入IOC容器的步骤
(1)在需要注入IOC容器的bean上面加上注解
(2)添加扫描基础包<context:component-scan>
(3) 要导入aop的jar包
<?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">
<!--
通过给bean上面加上某些注解,可以快速地将bean注入到IOC容器中
spring有四个注解
@Controller:控制器层
@Service:业务逻辑层
@component:通用
@Repository:持久层
这些注解都能将bean注入IOC容器,可以顺便选一个使用,
但是推荐按照上面写的加注解,方便别的程序员理解程序
使用注解将bean注入IOC容器的步骤
(1)在需要注入IOC容器的bean上面加上注解
(2)添加扫描基础包<context:component-scan>
(3)要导入aop的jar包
-->
<!--扫描基础包,把基础包及它以下所有的包加了注解的类,自动扫描进IOC容器-->
<context:component-scan base-package="com.sf.annotation"></context:component-scan>
</beans>
@Service public class BookService { }@Repository public class Dao { }@Controller public class Servelet { }
使用注解将bean注入IOC容器和使用配置将bean注入IOC容器默认
(1)组件id 类名的首字母小写,如下默认是servelet,@Controller("servelet1")这样就指定为了servelet1
(2)组件的作用域,默认是单例。使用注解@Scope()可以修改作用域,如下用@Scope(value = "prototype")将Servelet类修饰为多实例。
@Controller("servelet1")
@Scope(value = "prototype")
public class Servelet {
}
注解也不能完成所有bean的注入,如果是外部的程序就需要用配置的方式将其注入到容器里面。
context:exclude-filter使用这样的标签可以在扫描的时候排除一些不需要的组件
<!--扫描基础包,把基础包及它以下所有的包加了注解的类,自动扫描进IOC容器-->
<context:component-scan base-package="com.sf.annotation">
<!--扫描的时候可以排除一些不需要的组件,如下是排除了用Controller注解注入IOC容器的bean-->
<!--<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>-->
<!--扫描的时候可以排除一些不需要的组件,如下是排除了Servelet类的bean-->
<!--<context:exclude-filter type="assignable" expression="com.sf.annotation.controller.Servelet"></context:exclude-filter>-->
</context:component-scan>
默认是全部扫描进来的,所有要先将默认的过滤规则置为false,使用use-default-filters="false",再用context:include-filter来指定只扫描这些组件。
<context:component-scan base-package="com.sf.annotation" use-default-filters="false" >
<context:include-filter type="assignable" expression="com.sf.annotation.controller.Servelet"></context:include-filter>
</context:component-scan>
@Autowired注解:Spring会自动为这个属性赋值,一定是去容器中找到这个对应的组件。
@Controller
public class Servelet {
@Autowired
private BookService bookService;
public void save(){
bookService.save();
}
}