IOC操作Bean管理(基于注解方式)
1.什么是注解
- 注解是代码的特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值。。。)
- 使用注解,注解作用在类上面,方法声明,属性上面
- 使用注解的目的:简化xml配置,使用更优雅、更简洁的方式实现功能
2.Spring针对Bean管理中创建对象提供的注解
- @Component (建议普通的组件)
- @Service(建议用在Service层)
- @Controller(建议用在Web层)
- @Repository(建议用在持久层)
以上4个注解功能都是一样的,都可以用来创建bean实例
3.基于注解方式实现对象创建
-
引入依赖
-
jar包:
-
maven
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.0.7.RELEASE</version> </dependency>
-
-
开启组件扫描
-
在配置文件中引入centext文件空间
<?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:p="http://www.springframework.org/schema/p" 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"> </beans>
-
编写xml标签
<!-- 开启组件扫描 <context:component-scan></context:component-scan> base-package写法: 1.扫描多个包,多个包用逗号隔开 <context:component-scan base-package="com.yang.pojo,com.yang.dao"></context:component-scan> 2.扫描包的上层目录 <context:component-scan base-package="com.yang"></context:component-scan> --> <context:component-scan base-package="com.yang"></context:component-scan>
-
3.创建类,在类上添加创建对象注解
package com.yang.service;
import org.springframework.stereotype.Component;
/**
* @program: TestSpring
* @description: UserService层
* @author: 陈阳
* @create: 2021-01-24 21:12
**/
// 在注解里value属性值可以不写
// 默认值是类的名称,首字母小写
// UserService --- userService
@Component(value = "userService")//<bean id="userService" class="......." />
public class UserService {
public void add(){
System.out.println("service层的添加方法");
}
}
- 测试是否可用
1.测试代码:package com.yang.run; import com.yang.service.UserService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @program: TestSpring * @description: 测试注解方式是否可用 * @author: 陈阳 * @create: 2021-01-24 21:19 **/ public class TestAnn { @Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); UserService userService = context.getBean("userService", UserService.class); userService.add(); } }
- 测试结果: