Spring基于注解的配置

周一了!!!工作日盼周末,周末盼工作日,人就是这么纠结!!!给自己一点正能量,今年的目标:转到Java后端,并且薪资上涨2k;

学习地址:https://www.w3cschool.cn/wkspring/43851h9t.html

@Required注释

@Required注释应用于bean属性的setter方法,它表明受影响的bean属性在配置时必须放在XML配置文件中,否则容器会抛出一个BeanInitializationException异常;用 我自己理解的话说:就是你在哪个属性的setter方法那里写了@Required注释,那么你在配置文件XML的时候,就必须把这个属性的值写在里面,不写就会报错。下面这个例子就可以看出来!!!

实例:

Student.java:

package com.lee.required;

import org.springframework.beans.factory.annotation.Required;

public class Student {
    private Integer age;
    private String name;

    public Integer getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

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

}

这里的name属性和age属性的setter方法都有@Required注释,所有在Beans.xml配置的时候,这两个属性得在bean里面提现

MainApp.java:

package com.lee.required;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        Student st = (Student) context.getBean("student");

        System.out.println("Name: " + st.getName());
        System.out.println("Age: " + st.getAge());

    }

}

 

Beans.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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config />

    <bean id="student" class="com.lee.required.Student">
        <property name="name" value="LiLe"></property>
        <property name="age" value="20"></property>
    </bean>

</beans>

这里的property标签里必须得把上面的name和age属性都写上;不然会报错;

注解连线在默认情况下再Spring容器中不打开;因此,在可以使用基于注解的连线之前,需要在Spring配置文件中启用它。在上面标红的为新加的!!!

这里假如把<property name="age" value="20"></property> 注释掉,则报错如下:

猜你喜欢

转载自www.cnblogs.com/lemon-le/p/9316214.html