Spring配置Bean-注解方式

122 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第23天,点击查看活动详情


1 在 classpath 中扫描组件

  • 组件扫描(component scanning): Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件。

  • 特定组件包括:

    • @Component: 基本注解, 标识了一个受 Spring 管理的组件
    • @Respository: 标识持久层组件
    • @Service: 标识服务层(业务层)组件
    • @Controller: 标识表现层组件
  • 对于扫描到的组件, Spring 有默认的命名策略: 使用非限定类名, 第一个字母小写. 也可以在注解中通过 value 属性值标识组件的名称。

  • 当在组件类上使用了特定的注解之后, 还需要在 Spring 的配置文件中声明 <context:component-scan>

    • base-package 属性指定一个需要扫描的基类包,Spring 容器将会扫描这个基类包里及其子包中的所有类。
    • 当需要扫描多个包时, 可以使用逗号分隔。
    • 如果仅希望扫描特定的类而非基包下的所有类,可使用 resource-pattern 属性过滤特定的类。
    • <context:include-filter> 子节点表示要包含的目标类。
    • <context:exclude-filter> 子节点表示要排除在外的目标类。
    • <context:component-scan> 下可以拥有若干个 <context:include-filter><context:exclude-filter> 子节点。

2 示例

使用@Component注解,TestObject.java:

package site.exciter.spring.annotation;

import org.springframework.stereotype.Component;

@Component
public class TestObject {
    
}

使用@Repository注解

接口类IUserRepository.java:

package site.exciter.spring.annotation.repository;

public interface IUserRepository {

    void save();

}

实现类UserRepositoryImpl.java:

package site.exciter.spring.annotation.repository;

import org.springframework.stereotype.Repository;

@Repository("userRepository")
public class UserRepositoryImpl implements IUserRepository {

    @Override
    public void save() {
        System.out.println("UserRepositoryImpl save");
    }
}

使用@Service注解,UserService.java:

package site.exciter.spring.annotation.service;

import org.springframework.stereotype.Service;

@Service
public class UserService {

    public void add() {
        System.out.println("UserService add");
    }

}

使用@Controller注解,UserController.java:

package site.exciter.spring.annotation.controller;

import org.springframework.stereotype.Controller;

@Controller
public class UserController {

    public void execute() {
        System.out.println("UserController execute");
    }

}

在Spring配置文件中:

<?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: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-4.2.xsd">

    <!--使用component-scan指定IOC容器扫描的包-->
    <context:component-scan base-package="site.exciter.spring.annotation"/>

</beans>

测试:

package site.exciter.spring.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import site.exciter.spring.annotation.controller.UserController;
import site.exciter.spring.annotation.repository.IUserRepository;
import site.exciter.spring.annotation.repository.UserRepositoryImpl;
import site.exciter.spring.annotation.service.UserService;

public class Test {

    @org.junit.Test
    public void testAnnotation() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans-annotation.xml");

        TestObject testObject = (TestObject) context.getBean("testObject");
        System.out.println(testObject);

        UserController userController = (UserController) context.getBean("userController");
        System.out.println(userController);

        UserService userService = (UserService) context.getBean("userService");
        System.out.println(userService);

        IUserRepository userRepository = (UserRepositoryImpl) context.getBean("userRepository");
        System.out.println(userRepository);
    }
}

Log:

site.exciter.spring.annotation.TestObject@75f32542
site.exciter.spring.annotation.controller.UserController@7f1302d6
site.exciter.spring.annotation.service.UserService@43ee72e6
site.exciter.spring.annotation.repository.UserRepositoryImpl@23529fee

Process finished with exit code 0

3 resource-pattern 扫描指定的资源

 <!--使用component-scan指定IOC容器扫描的包
        resource-pattern:指定扫描的资源,如下面示例就只能扫描controller包下的资源
    -->
    <context:component-scan base-package="site.exciter.spring.annotation"
                            resource-pattern="controller/*.class"/>

4 context:exclude-filter 排除目标

注意expression的不同

方式1 type="annotation"

    <!--排除目标:不扫描某个注解-->
    <context:component-scan base-package="site.exciter.spring.annotation">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    </context:component-scan>

方式2 type="assignable"

    <!--    type="assignable":不包含    -->
    <context:component-scan base-package="site.exciter.spring.annotation">
        <context:exclude-filter type="assignable"
                                expression="site.exciter.spring.annotation.repository.IUserRepository"/>
    </context:component-scan>

5 context:include-filter 包含目标

注意expression的不同

方式1 type="annotation"

 <!--包含目标:只扫描指定的注解 include-filter和use-default-filters配合使用-->
    <context:component-scan base-package="site.exciter.spring.annotation" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

方式2 type="assignable"

 <!--    <context:include-filter> type="assignable":只包含    -->
    <context:component-scan base-package="site.exciter.spring.annotation" use-default-filters="false">
        <context:include-filter type="assignable"
                                expression="site.exciter.spring.annotation.repository.IUserRepository"/>
    </context:component-scan>

6 自动装配

<context:component-scan> 元素还会自动注册 AutowiredAnnotationBeanPostProcessor 实例, 该实例可以自动装配具有 @Autowired 和 @Resource 、@Inject注解的属性。

使用@Autowired自动装配Bean

@Autowired 注解自动装配具有兼容类型的单个 Bean属性

  • 构造器, 普通字段(即使是非 public), 一切具有参数的方法都可以应用@Authwired 注解。
  • 默认情况下, 所有使用 @Authwired 注解的属性都需要被设置. 当 Spring 找不到匹配的 Bean 装配属性时, 会抛出异常, 若某一属性允许不被设置, 可以设置 @Authwired 注解的 required 属性为 false。
  • 默认情况下, 当 IOC 容器里存在多个类型兼容的 Bean 时, 通过类型的自动装配将无法工作. 此时可以在 @Qualifier 注解里提供 Bean 的名称;Spring 允许对方法的入参标注 @Qualifiter 已指定注入 Bean 的名称。
  • @Authwired 注解也可以应用在数组类型的属性上, 此时 Spring 将会把所有匹配的 Bean 进行自动装配.。
  • @Authwired 注解也可以应用在集合属性上, 此时 Spring 读取该集合的类型信息, 然后自动装配所有与之兼容的 Bean。
  • @Authwired 注解用在 java.util.Map 上时, 若该 Map 的键值为 String, 那么 Spring 将自动装配与之 Map 值类型兼容的 Bean, 此时 Bean 的名称作为键值。

使用@Resource或@Inject自动装配Bean

  • Spring 还支持 @Resource 和 @Inject 注解,这两个注解和 @Autowired 注解的功用似。
  • @Resource 注解要求提供一个 Bean 名称的属性,若该属性为空,则自动采用标注处的变量或方法名作为 Bean 的名称。
  • @Inject 和 @Autowired 注解一样也是按类型匹配注入的 Bean, 但没有 reqired 属性建议使用@Autowired 注解。
@Controller
public class UserController {

    @Autowired
    UserService userService;

    public void execute() {
        System.out.println("UserController execute");
        userService.add();
    }

}

关注木水小站 (zhangmushui.cn)和微信公众号【木水Code】,及时获取更多最新技术干货。