二、IOC注解
1、注解需要导入aop的jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
2、Spring针对bean管理提供的注解
存在4个创建Bean实例,功能一致,只是对应不同的层
- @Component
- @Controller
- @Service
- @Repository
3、基于注解的对象创建
-
引入依赖spring-aop
-
在配置文件中开启组件扫描
<!-- 开启组件扫描--> <!-- 如果扫描多个包,可以使用逗号隔开--> <context:component-scan base-package="day01.domain"></context:component-scan>
-
创建类,在类上面添加创建对象注解(@Component、@Controller、@Service、@Respository)
@Component("user") //等价于 <bean id="user" class="..."> //仅使用 @Compinent bean的id为类名的首字母小写 public class User { }
4、组件扫描的注意点
-
关于<context:include>
<!-- use-default-filters="false" 表示不使用默认的filter,自己配置filter--> <!-- context:include-filter 表示要扫描那些内容--> <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 表示只扫描带有Controller注解的类--> <context:component-scan base-package="day01.annotation" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
-
关于<context:exclude>
<!-- <context:exclude-filter 表示不扫描包下带有Controller注解的类--> <context:component-scan base-package="day01.annotation"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
5、基于注解的属性注入
-
@Autowired : 根据属性类型进行自动装配
//不需要添加setter方法了,底层已经完成了 @Autowired private UserDao userDao;
-
@Qualifier : 根据属性名称进行注入,要和@Autowired一起使用
@Autowired @Qualifier(value = "userDaoImpl") private UserDao userDao;
-
@Resource : 根据类型注入,也可以根据名称注入@Resource(name="")不是spring中的注解
@Resource//或者@Resource(name = "userDaoImpl") private UserDao userDao;
-
@Value : 注入普通类型属性
@Value("张三") private String name;
6、全注解开发(多用于springboot)
-
配置类
@Configuration //表示这个一个配置类,用来代替xml文件 @ComponentScan(basePackages = {"day01.annotation"})//表示包扫描 public class SpringConfig { }
-
测试类
/** * 用来测试全注解 * AnnotationConfigApplicationContext */ @Test public void test2(){ ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); UserService service = context.getBean("userServiceImpl", UserService.class); service.service(); }