JavaRush/Java Blog/Random EN/Spring. Lesson 4: The value attribute for embedding value...

Spring. Lesson 4: The value attribute for embedding values

Published in the Random EN group
members
And so... We continue our course on Spring. In the last lesson we studied dependency injection using a setter. If you noticed, then we implemented values ​​using links to id. That is, the implementation took place using the ref attribute. It looked something like this: Listing 1
<bean id="javaDeveloper" class="org.example.JavaDevelopment"/>

<bean id="hiringDepartment" class="org.example.HiringDepartment">
        <property name="development" ref="javaDeveloper"/>
</bean>
Here 4 - line refers to the id "javaDeveloper", which implements the value of the JavaDevelopment class. What if we want to inject the values ​​manually or get it some other way and then inject it. Let's look at an example. Each employee has a citizenship and salary. And let these entities be defined in the HiringDepartment class. Let's say this: Listing 2
package org.example;

public class HiringDepartment {
    private Development development; //Определяем интерфейс
    private int salary;
    private String citizenship;

    public void displayInfo(){
        System.out.println("Name: " + development.getName());
        System.out.println("Job: " + development.getJob());
    }

    public void setDevelopment(Development development){
        this.development = development;
    }

    public Development getDevelopment(){
        return development;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public String getCitizenship() {
        return citizenship;
    }

    public void setCitizenship(String citizenship) {
        this.citizenship = citizenship;
    }
}
Here we have added 2 fields. int salary and String citizenship . We also defined getters and setters for these objects. As a reminder, Spring refers to these getters and setters behind the scenes to bind values ​​to class objects. We are not touching other classes yet. And then we will redo the applicationContext file, which defines the beans for our objects. And it looks like this: Listing 3
<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="javaDeveloper" class="org.example.JavaDevelopment"/>
    <bean id="pythonDeveloper" class="org.example.PythonDevelopment"/>

    <bean id="hiringDepartment" class="org.example.HiringDepartment">
        <property name="development" ref="javaDeveloper"/>
        <property name="citizenship" value="USA"/>
        <property name="salary" value="5000"/>
    </bean>

</beans>
Unlike Listing 1, two more properties have been added here (lines 12 and 13). This is where the value attribute comes into play , which is defined inside the property tag. Let me remind you once again that the value of the name attribute must match the object that the bean refers to. And then Spring independently determines getters and setters using these values. And using the value attribute we implement values ​​for the fields. Note that both value values ​​are defined in quotes, although this is unusual for the int type. But Spring, as always, determines which value should be associated with which type. This happens due to the name attribute . By the name of the bean, Spring refers to an object of the class and determines the type of this object. Well, that's all. Now all that remains is to check our updates in the Main class: Listing 5
package org.example;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String ... args){
        //Определяем контекст файл в котором содержатся прописанные нами бины
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //Получем бины, которые были определены в файле applicationContext.xml
        HiringDepartment hiringDepartment = context.getBean("hiringDepartment", HiringDepartment.class);

        hiringDepartment.displayInfo();
        System.out.println("Citizenship: " + hiringDepartment.getCitizenship());
        System.out.println("Salary: " + hiringDepartment.getSalary());
        context.close(); //Контекст всегда должен закрываться
    }
}
There's no need to change much here. Only to obtain results we call getters of the HiringDepartment class using the standard output stream. As a result, we get the following answer:
Name: Alexa
Job: Middle Java developer
Citizenship: USA
Salary: 5000
OK. Let’s say we have 10 such employees who have the same citizenship and receive the same salary. And let’s say the company decided to increase their salaries. Then you will have to manually change all these 10 values. It's too boring. What if we define these values ​​in a separate file and associate these values ​​with beans? Then we would only have to change the value once in this file, and the remaining beans that reference this value would change automatically. Let's try it... To do this, we'll make some updates in the project structure and in the applicationContext.xml file. First, in the resources folder, add a new file with the extension .properties . I named this file "myApp.properties". Now the project structure has taken on the following form: Spring.  Lesson 4. The value attribute for embedding values ​​- 1 And in the file we will write the following values:
employee.citizenship="Russia"
employee.salary=6000
To the left of the "=" sign are the names of the variables (if they can be called that), and to the right are the values ​​of these variables. You can give the name whatever you like, but as usual, with meaning. And yes, the period here plays a strategic role, not a syntactic one. Let's say we also have managers, also with their own salaries. Then we can simply name these variables something like this: manager.salary. That is, the names of the variables will not coincide and interfere with each other. Now let's update the applicationContext.xml file. Before declaring beans, you must write the following line:
<context:property-placeholder location="classpath:myApp.properties"/>
Here we define the file we created to embed the values. And then in the value attribute we put a dollar sign $ in double quotes and in curly brackets {} we write the name of the variable from the myApp.properties file:
<property name="salary" value="${employee.salary}"/>
As a result, Spring looks up this variable, gets its value, and attaches it to the class object. The complete code looks like this: Listing 6
<?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.xsd">

    <context:property-placeholder location="classpath:myApp.properties"/>

    <bean id="javaDeveloper" class="org.example.JavaDevelopment"/>
    <bean id="pythonDeveloper" class="org.example.PythonDevelopment"/>

    <bean id="hiringDepartment" class="org.example.HiringDepartment">
        <property name="development" ref="javaDeveloper"/>
        <property name="citizenship" value="${employee.citizenship}"/>
        <property name="salary" value="${employee.salary}"/>
    </bean>

</beans>
Let's launch the program:
Name: Alexa
Job: Middle Java developer
Citizenship: "Russia"
Salary: 6000
As always, the best way to learn programming is to program. Repeat what you have learned yourself, try to update elements, play with the code. In short, go for it. And that's all for me. Thank you for your attention! Source code at the link My GitHub Join my telegram channel Course content To be continued...
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet