目录
什么是注解
(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值..)。
(2)使用注解,注解作用在类上面,方法上面,属性上面。
(3)使用注解目的:简化 xml 配置。
Spring 针对 Bean 管理中创建对象提供注解
(1)@Component
(2)@Service
(3)@Controller
(4)@Repository
* 上面四个注解功能是一样的,都可以用来创建 bean 实例
但是我们有时候会根据约定在不同的类上使用不同的注解,比如我们在普通的组件上面会使用@Component,在Service上使用@Service,在控制器上使用@Controller,在Dao上使用@Repository。
基于注解方式实现对象创建
引入依赖
我们是通过Maven来构建项目的
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.16</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
开启组件扫描
在xml配置文件中开启组件扫描
这个是整个的xml的内容
<?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:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.csdn.bz"></context:component-scan>
</beans>
创建类,在类上面添加创建对象注解
@Service(value = "userService")
public class UserService {
public void execute(){
System.out.println("userService's execute()");
}
}
测试
基于注解方式实现属性注入
(1)@Autowired:根据属性类型进行自动装配
我们创建UserDao接口,并创建其实现类UserDaoImpl。并在UserService类中使用UserDaoImpl。
调用测试
(2)@Qualifier:根据名称进行注入
我们知道,在开发的过程中一个接口是会有很多实现类的,比如现在我们的UserDao再增加一个实现类UserDaoImpl2
此时若执行我们之前写的测试方法就会报错,因为之前的Autowired时根据类型来注入属性的,现在有多于1个的UserDao类型的对象。
错误信息如下:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userDao'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.csdn.bz.dao.UserDao' available: expected single matching bean but found 2: userDaoImpl,userDaoImpl2
此时我们需要使用Qualifier来指定名字
@Value:注入普通类型属性
我们在UserService中加入一个属性name用于测试
执行测试方法得到结果
完全注解开发
完全注解开发就是不使用我们之前的xml配置文件,而使用一个配置类来完成。
删除之前的xml配置文件
这里的操作就不用说了吧,直接把xml配置文件delete调就可以了。
写配置类(就相当于我们之前的xml配置文件)
@Configuration
@ComponentScan(basePackages = {"com.csdn.bz.dao","com.csdn.bz.service"})
public class SpringConfig {
}
测试
由于现在已经删除了xml配置文件使用的是注解类的方式,因此我们在进行测试的时候需要修改一下方式。
@Test
public void test2(){
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userSerivce = ac.getBean("userService", UserService.class);
userSerivce.execute();
}