Spring -- Spring IOC, annotation based automatic seedling burning

Keywords: JDBC xml Spring Attribute

1. Parameter configuration mode of set [List,Set,Map] and configuration file []

applicationContext.xml

<!--Set and configuration parameter injection mode -->
<bean id="example" class="cn.goktech.entity.Example">
    <property name="interest">
        <list>
            <value>sing</value>
            <value>dance</value>
            <value>rap</value>
        </list>
    </property>
    <property name="cities">
        <set>
            <value>Beijing</value>
            <value>Chengdu</value>
            <value>Shanghai</value>
        </set>
    </property>
    <property name="like">
        <map>
            <entry key="Chinese" value="Chinese" />
            <entry key="Math" value="Mathematics" />
            <entry key="English" value="English?"/>
        </map>
    </property>
    <property name="info">
        <props>
            <prop key="username">Alice</prop>
            <prop key="password">123456</prop>
            <prop key="driver">com.jdbc.mysql.driver</prop>
        </props>
    </property>
</bean>

Test class, output the value in set collection

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        Example e = context.getBean(Example.class);
        System.out.println(e.getCities());
    }
}

2. Use of util tag and how util references local configuration file

<property name="cities" ref="diySet"> 
<!--Dependency injection id by diySet Of Set Injection, no sequence, execute after loading -->
<!--            <set>-->
<!--                <value>Beijing</value>-->
<!--                <value>Chengdu</value>-->
<!--                <value>Shanghai</value>-->
<!--            </set>-->
        </property>
<!--util Define reusable sets -->
<util:set id="diySet"> <!--Define a collection for global use, which can be given id Scope of action -->
    <value>Lanzhou</value>
    <value>Zhengzhou</value>
    <value>Guangzhou</value>
</util:set>
<!-- spring-expression jar In bag util Of jar package-->

Operation result:

3.Spring EL expression

jdbc.properties configuration file

url=jdbc:mysql://localhost:3306/test
username=root
password=123456
driver=com.mysql.jdbc.Driver

applicationContext.xml

<!--    Reference profile, localhost Develop local profile path -->
    <util:properties id="jdbc" location="jdbc.properties" />
<!--    Spring EL Expression #{id.attribute} -->
    <bean id="myConnection" class="cn.goktech.entity.MyConnection">
        <property name="url" value="#{jdbc.url}"/>
        <property name="driver" value="#{jdbc.driver}" />
        <property name="username" value="#{example.interest[2]}" />
        <property name="password" value="#{example.like.Chinese}" />
    </bean>

Class Test

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        Example e = context.getBean(Example.class);
        System.out.println(e.getCities());
        System.out.println(e.getInfo().get("driver"));
        System.out.println("----------------");
        MyConnection connection = context.getBean(MyConnection.class);
        System.out.println(connection.getUrl());
        System.out.println(connection.getUsername());
        System.out.println(connection.getPassword());
    }
}

Output results:

4. Auto assemble the autowired attribute

Spring can automatically assemble the dependency between Bean and Bean, that is, instead of explicitly specifying the dependency Bean with ref attribute, spring container checks the content of XML configuration file.
Note: automatic assembly can reduce the workload of configuration files, but reduce the transparency and certainty of dependencies.

applicationContext.xml

<! -- auto assembly: defau lt does not use auto assembly, byName looks for the ID of the bean consistent with the property name -- >
<bean id="a" class="cn.goktech.entity.A" />
<bean id="b" class="cn.goktech.entity.B" autowire="byName" />

byName method: if the id is modified, it cannot be found
Class Test:

B b = context.getBean(B.class);
b.getA().af();
public class A {
    public A(){
        System.out.println("A Construction execution of class");

    }
    public void af(){
        System.out.println("A Class method call succeeded");
    }
}
public class B {
    private A a;
    public B(){
        System.out.println("B Construction execution of class");
    }
    public B(A a){
        this.a = a;
    }

    public A getA() {
        return a;
    }

    public void setA(A a) {
        this.a = a;
    }
}

Operation result:

(1) no: the default value. no auto assembly is used. The bean dependency is completely defined by ref element. In a larger deployment environment, changing this configuration is not encouraged, which can make the dependency between beans clearer.
(2) byName: the Spring container uses the property name as the id to find the corresponding bean, and calls the set method to complete the injection

<bean id="a" class="cn.goktech.entity.A" />
<bean id="b" class="cn.goktech.entity.B" autowire="byName" /> <!--stay B Injection in class A class -->

Note: Spring will only search by name, even if the type does not match, injection will occur, just throw a type conversion exception during injection. Inject null if the bean is not found.
(3) the byType:Spring container looks for the bean that is consistent with the class attribute type, and then calls the set method to inject.
Not applicable when there are more than one class with the same name.
Note: if multiple bean s of the same type are found in the xml configuration file, an exception is thrown.
(4) the constructor: container looks for the bean that is consistent with the class attribute type, and then calls the constructor to complete it.

5. Automatic scanning based on annotation

(1) Importing jar packages of aop and aspects
(2) Add scan configuration < context: component scan base package = "" >
(3) Comments [@ composnet, @ value, @ autowire, @ resource]

<! -- auto scan based on annotation, specify a package, and scan all classes in the package and its subpackages -- >
<context:component-scan base-package="cn.goktech.anno"/>

Add @ Component before the Student class and @ Component before the Teacher class

@Component
public class Student {
    @Value("1001")
    private int id;

    @Value("Alice")
    private String name;

    //Injection object, setter injection recommendation @ Resource, constructor injection recommendation @ Autowire
    @Autowired
    private Teacher teacher;
@Component
public class Teacher {
    @Value("001")
    private int id;

    @Value("#{jdbc.teacher}") //Configure teacher = Han teacher in jdbc, and the EL expression is equivalent to @ Value("Han teacher")
    private String name;

Annotations and configurations can be called on each other.

TestAnno

public class TestAnno {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        Student s = context.getBean(Student.class);
        System.out.println(s.getName()+"-"+s.getTeacher().getName());
    }
}

Output results:

Once scanned, the bean is configured.
Injection object, setter injection recommendation @ Resource, constructor injection recommendation @ Autowire
@Resource can only be used for setter injection, while @ Autowire can be used for both setter injection and constructor injection

94 original articles published, praised 26, visited 30000+
Private letter follow

Posted by CrimsonSoul on Tue, 17 Mar 2020 03:47:19 -0700