Spring注解方式管理Bean

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第16天,点击查看活动详情

虽然Spring以简化开发著称,但在学习的过程中我们发现,每新建一个类,就需要在配置文件中进行配置,并且类与类之间的关系也需要配置在标签中,好像这并没有简化我们的开发,反而增加了很多繁琐的配置。别担心,本篇文章我们就来学习一下用注解方式来管理Bean。

组件扫描

大家不要对组件这个词感到陌生,在Spring中,一个类可以被称为Bean,也被称为一个组件,回想一下,在之前,我们如何将一个组件注册到IOC容器中呢?没错,我们需要写一段配置,例如:

<bean id="user" class="com.wwj.spring.demo.User">
  <property name="name" value="zs"/>
  <property name="age" value="22"/>
</bean>
复制代码

为了让大家从繁琐的配置中解脱出来,Spring提供了一种基于注解的管理方式,Spring提供了以下注解用来注册一个组件:

  1. @Component
  2. @Controller
  3. @Service
  4. @Repository

这四个注解都可以用来注册一个组件,不过每个注解都有其意义,比如@Controller,它是用来注册一个前端控制器的,我们将在SpringMVC中对其进行详解;而@Service是用来注册一个服务层对象的;@Repository是用来注册一个持久层对象的。来体验一下它们的强大吧:

@Component
public class User {
    private String name;
    private Integer age;
}

public interface UserService {
}

@Service
public class UserServiceImpl implements UserService {
}

@Repository
public interface UserRepository {
}
复制代码

我们从容器中取出所有的组件,看看注册是否成功了:

public static void main(String[] args) throws Exception {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    String[] beanDefinitionNames = context.getBeanDefinitionNames();
    for (String beanDefinitionName : beanDefinitionNames) {
        System.out.println(beanDefinitionName);
    }
}
复制代码

当你运行这段测试代码时你会发现控制台没有任何输出,是我们获取的方式不对吗?不对,其实我们还需要进行一项配置:

<context:component-scan base-package="com.wwj.spring.demo"/>
复制代码

运行结果:

user
userRepository
userServiceImpl
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
复制代码

可以看到我们的组件确实注册到Spring中了,剩下的是一些Spring内置的组件,我们无需关系。

\

context:component-scan标签是用来进行组件扫描的,其中base-package属性用于配置需要扫描的包,一般情况下我们会扫描项目的顶包,即:最外层的包,这样所有项目中的组件都会被扫描到并注册。

事实上,@Component、@Controller、@Service、@Repository四个注解的作用是完全一样的,你也可以在组件上随意地使用它们,比如:

@Repository
public class UserServiceImpl implements UserService {
}

@Service
public interface UserRepository {
}
复制代码

这是完全没有问题的,因为@Service、@Controller、@Repository注解是由@Component注解衍生出来的,但为了规范,还是建议将注解添加到指定的组件上。

自动注入

还记得Spring中的属性注入吗?如果不记得的话,我们来回顾一下:

public class User {
    private Pet pet;
}
复制代码

若是想将一个对象属性注入进去,我们需要进行配置:

<bean id="pet" class="com.wwj.spring.demo.Pet"/>
<bean id="user" class="com.wwj.spring.demo.User">
  <property name="pet" ref="pet"/>
</bean>
复制代码

但Spring提供了一种更加便捷的注入方式,自动注入

public class User {
    
    @Autowired
    private Pet pet;
}
复制代码

只需在User类的对象属性上添加@Autowired注解即可将Pet对象自动注入进来,而且它非常智能,我们对程序进行一些改造,首先去掉Pet类的@Component注解:

public class Pet {

    private String name;
    private Integer age;
}
复制代码

然后添加一个Dog类继承Pet,并注册:

@Component
public class Dog extends Pet{
    private String name;
    private Integer age;
}
复制代码

来测试一下:

public static void main(String[] args) throws Exception {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    User user = context.getBean("user", User.class);
    System.out.println(user.getPet().getClass());
}
复制代码

运行结果:

class com.wwj.spring.demo.Dog
复制代码

这样Dog类就被自动注入到User中了,但如果我们又创建了一个类继承Pet并注册:

@Component
public class Cat extends Pet{
}
复制代码

此时程序就会报错:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.wwj.spring.demo.Pet' available: expected single matching bean but found 2: cat,dog
复制代码

这是Spring中比较常见的一个异常,意思是期望单个匹配的Bean:Pet,但是匹配到了两个Bean:cat、dog。

错误非常好理解,因为Pet的子类有两个,所以Spring也不清楚我们到底想要哪一个Bean,所以抛出了异常。

这一问题会在Service层中出现,比如:

public interface UserService {
}

@Service
public class UserServiceImpl implements UserService {
}

@Service
public class EmployeeServiceImpl implements UserService {
}
复制代码

现在我们有一个UserService接口,并且有两个实现类,当自动注入UserService时显然会报错,那么如何解决这一问题呢?我们可以使用@Qualifier注解:

@Component
public class User {

    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;
}
复制代码

该注解的值即为需要注入的组件名,如果没有配置组件名,则默认是类名且首字母小写,当然了,我们也可以进行配置:

@Service("esi")
public class EmployeeServiceImpl implements UserService {
}
复制代码

注入方式如下:

@Component
public class User {

    @Autowired
    @Qualifier("esi")
    private UserService userService;
}
复制代码

这一问题也可以使用@Primary注解解决:

@Service
@Primary
public class UserServiceImpl implements UserService {
}
复制代码

当出现多个类型相同的类导致Spring无法选择时,如果某个类标注了@Primary,Spring将优先将该组件注册到IOC容器,不过这种方式确实不太优雅。

@Resource注解

刚才的问题其实可以通过换一个注解来解决,我们不妨试试看:

@Component
public class User {

    @Resource
    private UserService userService;
}
复制代码

@Resource注解是JSR-250定义的注解,它和Spring没有关系,但能够实现和@Autowired注解相同的功能,我们先来介绍一下这两个注解之间的区别:

\

  • @Autowired默认按类型进行注入,若要按名称注入,则需要配合@Qualifier注解一起使用;@Resource既支持类型注入,也支持名称注入,默认为名称注入
  • @Autowired能够标注在构造器、方法、参数、成员变量、注解上;@Resource只能标注在类、成员变量和方法上
  • @Autowired是Spring提供的注解,脱离了Spring框架则无法使用;@Resource是JSR-250定义的注解,可以脱离任何框架使用

现在问题就解决了吗?其实并没有,当你运行测试代码时程序仍然会抛出异常,这是因为虽然@Resource默认为名称注入,但是在使用名称找不到组件的情况下,会继续使用类型注入,所以眼熟的异常就又出现了。

我们已经知道,Spring在扫描组件时会将类名且首字母小写作为组件的名称注入到IOC容器中,所以像这样注入就是没有问题的:

@Component
public class User {

    @Resource
    private UserService userServiceImpl;
}
复制代码

不过一般情况下我们不会这么写,而是像这样:

@Component
public class User {

    @Resource(name = "employeeServiceImpl")
    private UserService userService;
}
复制代码

通过@Resource注解,我们就解决了@Autowired和@Qualifier两个注解组合才能解决的问题,至于到底用哪个,还是看大家的使用习惯了。

@Value

可能有同学有疑问了,我知道对象类型的属性如何注入了,那基本类型数据如何注入呢?@Value注解能够帮助到你,使用方法如下:

@Component
public class User {

    @Value("zs")
    private String name;
    @Value("20")
    private Integer age;
}
复制代码

不过一般情况下,我们都不会把数据这样写死,都会将其放到配置文件中:

jdbc.url=jdbc:mysql:///test
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root
复制代码

此时需要借助一个新注解@PropertySource将值注入到指定的组件中:

@Component
@PropertySource("classpath:jdbc.properties")
public class User {

    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
}
复制代码

@Value还能够注入操作系统属性:

@Component
public class User {

    @Value("#{systemProperties['os.name']}")
    private String name;
}
复制代码

还可以注入表达式计算后的结果:

@Component
public class User {

    @Value("#{ T(java.lang.Math).random() * 100.0 }")
    private String result;
}
复制代码

猜你喜欢

转载自juejin.im/post/7087915777969356813