IOC操作 - 基于注解
一、注解
-
概念
是代码的特殊标记,详见 Java五十九: 注解 Annotation_e_n的博客
-
格式
@注解名称(属性名称=属性值,属性名称=属性值,…)
-
作用范围
类、方法、属性
-
目的
简化xml配置,使其更优雅简洁
二、创建对象
-
使用到的四个注解
① @Component
用于Spring容器中提供的普通组件
② @Service
用于业务逻辑层
③ @Controller
用于web层
④ @Repository
用于dao层
-
引入依赖
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ixz4YJcZ-1650896352728)(F:\MarkDown学习\图片素材-1\Spring\IOC-注解\注解所需依赖.jpg)]
-
在spring配置文件中开启组件扫描
<?xml version="1.0" encoding="UTF-8"?> <!-- 添加context名称空间 --> <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"> <!-- 开启组件扫描 1.如果扫描多个包,多个包使用逗号隔开 2.扫描包的上层目录 --> <context:component-scan base-package="com.atguigu.service,com.atguigu.dao"> </context:component-scan> <context:component-scan base-package="com.atguigu"></context:component-scan> </beans>
-
创建类,在类上面添加创建对象注解
// 注解内的值可以不写,默认值是类名的首字母小写 @Service(value="userService") public class UserService { public void add() { System.out.println("serviceceng"); } }
-
开启组件扫描的注意点
<!-- 示例1 use-default-filters="false":表示现在不使用默认filter,自己配置filter context:include-filter:设置扫描哪些内容 --> <context:component-scan base-package="com.atguigu" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 示例2 不 加:use-default-filters,表示扫描全部 再使用:context:exclude-filter:设置不扫描哪些内容 --> <context:component-scan base-package="com.atguigu"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
三、注入属性
-
四个常用注解
① @Autowired
根据属性类型进行自动装配
② @Qualifier
根据属性名称进行注入
和@Autowired一起使用,因为当接口有多个实现类时,根据接口类型匹配到多个类,再使用@Qualifier锁定属性名称即可准确定位
③ @Resource
可根据类型注入,也可根据属性名称注入
④ @Value
注入普通类型属性
-
代码示例
// 注解内的值可以不写,默认值是类名的首字母小写 @Service public class UserService { @Value(value = "abc") private String name; // @Autowired // @Qualifier(value = "userDAOImpl2") @Resource(name = "userDAOImpl2") private UserDAO userDAO; public void add() { System.out.println("service - add..."+name); userDAO.add(); } } @Repository(value="userDAOImpl2") public class UserDAOImpl implements UserDAO{ @Override public void add() { System.out.println("dao - add..."); } }
四、完全注解开发
-
创建配置类,替代xml配置文件
/* @Configuration:表明该类时配置类 @ComponentScan:指明扫描范围 */ @Configuration @ComponentScan(basePackages = {"com.atguigu"}) public class SpringConfig { }
-
测试类
public class TestSpring { @Test public void testSpring1() { // 加载类改为:AnnotationConfigApplicationContext AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); UserService userService = context.getBean("userService", UserService.class); userService.add(); } }