spring基于注解的配置

158 阅读2分钟

「这是我参与2022首次更文挑战的第9天,活动详情查看:2022首次更文挑战」。

前言

**不管是 XML 还是注解,它们都是表达 Bean 定义的载体,其实质都是为 Spring 容器提供 Bean 定义的信息,在表现形式上都是将 XML 定义的内容通过类注解进****行描述。**Spring 从2.0开始就引入了基于注解的配置方式,在2.5时得到了完善,在4.0时进一步增强。

我们知道,Spring 容器成功启动的三大要件分别是 Bean定义信息、Bean实现类及 Spring 本身。如果采用基于XML 的配置,则 Bean定义信息和 Bean实现类本身是分离的:而如果采用基于注解的配置文件,则 Bean定义信息通过在 Bean实现类上标注注解实现。

注解的使用

注解配置默认情况下在Spring中是关闭的,我们需要在配置文件中使用<context:annotation-config/>激活它。

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

    <context:annotation-config/>

</beans>

一旦激活注解配置后,我们就可以在代码中使用注解来进行依赖注入。其中下面是几个重要的注解:

@Required注解应用于bean属性的setter方法 @Autowired注解可以应用到bean属性的setter方法,非setter方法,构造函数和属性 @Qualifier,通过指定确切的将被引用的bean,@Autowired和@Qualifier注解可以用来删除混乱 JSR-250 Annotations,Spring支持JSR-250的基础的注解,其中包括了@Resource,@PostContruct和@PreDestory注解

@Required 注解

@Required 注解应用于 bean 属性的 setter 方法,它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常。

示例

下面显示的是一个使用 @Required 注解的示例。

创建一个Person类,

public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    @Required
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @Required
    public void setAge(int age) {
        this.age = age;
    }
 }

使用@Required注解了属性nameage的两个setter方法setName()setAge(),这表示我们在使用XML为Person类注入属性时必须注入这两个属性。

spring-config.xml文件配置如下:

  <context:annotation-config/>
    <bean id="person" class="com.gavin.domain.Person">
        <property name="age" value="20"/>
         <property name="name" value="zmj"/>
    </bean>

注意:@Required注解用于注解属性的setter方法,如果一个属性的setter方法被@Required注解,则表示在XML配置中,该属性一定要注入值,否则会报异常。