IOC 操作 Bean 管理(基于注解方式)
1、什么是注解
(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值…)
(2)使用注解,注解作用在类上面,方法上面,属性上面
(3)使用注解目的:简化 xml 配置
2、Spring 针对 Bean 管理中创建对象提供注解
下面四个注解功能是一样的,都可以用来创建 bean 实例
(1)@Component
(2)@Service
(3)@Controller
(4)@Repository
3、基于注解方式实现对象创建
第一步 引入依赖 (引入spring-aop jar包)
第二步 开启组件扫描
1 2 3 4 5
|
<context:component-scan base-package="com.atguigu"></context:component-scan>
|
第三步 创建类,在类上面添加创建对象注解
1 2 3 4 5 6 7 8 9
|
@Component(value = "userService") public class UserService { public void add() { System.out.println("service add......."); } }
|
4、开启组件扫描细节配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
<context:component-scan base-package="com.atguigu" use-defaultfilters="false"> <context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/> </context:component-scan>
<context:component-scan base-package="com.atguigu"> <context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/> </context:component-scan>
|
5、基于注解方式实现属性注入
(1)@Autowired:根据属性类型进行自动装配
第一步 把 service 和 dao 对象创建,在 service 和 dao 类添加创建对象注解
第二步 在 service 注入 dao 对象,在 service 类添加 dao 类型属性,在属性上面使用注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @Service public class UserService { @Autowired private UserDao userDao; public void add() { System.out.println("service add......."); userDao.add(); } }
@Repository
public class UserDaoImpl implements UserDao { @Override public void add() { System.out.println("dao add....."); } }
|
(2)@Qualifier:根据名称进行注入,这个@Qualifier 注解的使用,和上面@Autowired 一起使用
1 2 3 4 5 6
|
@Autowired
@Qualifier(value = "userDaoImpl1")
|
(3)@Resource:可以根据类型注入,也可以根据名称注入(它属于javax包下的注解,不推荐使用!)
1 2 3
| @Resource(name = "userDaoImpl1") private UserDao userDao;
|
(4)@Value:注入普通类型属性
1 2
| @Value(value = "abc") private String name
|
6、完全注解开发
(1)创建配置类,替代 xml 配置文件
1 2 3 4 5
| @Configuration @ComponentScan(basePackages = {"com.atguigu"}) public class SpringConfig { }
|
(2)编写测试类
1 2 3 4 5 6 7 8 9 10
| @Test public void testService2() { ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); UserService userService = context.getBean("userService", UserService.class); System.out.println(userService); userService.add(); }
|