Spring dependency injection bean properties, manual assembly using xml configuration, SpEL expressions, collection List, Set, Map, Properties injection, array injection, annotation injection-day02

The first section Spring dependency injection bean properties (xml)

1.1 Manual assembly, use xml configuration

1. Inject by constructing method

  1. Write a Student class, provide get/set, toString, no parameter structure, 2 different parameter structures
    Insert picture description here
  2. 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"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--通过构造方法注入属性的值-->
    <!--<bean class="com.it.model.Student" id="student">
        &lt;!&ndash;这样写就调用的是2个string的构造方法&ndash;&gt;
        <constructor-arg name="username" value="shu"></constructor-arg>
        <constructor-arg name="password" value="123"></constructor-arg>
    </bean>-->

    <!--<bean class="com.it.model.Student" id="student">
        &lt;!&ndash;这样写就调用的是一个string 一个是int 的构造方法&ndash;&gt;
        <constructor-arg name="username" value="shu"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
    </bean>-->

    <bean class="com.it.model.Student" id="student">
        <!--还可以通过索引加类型,给构造方法赋值-->
        <constructor-arg index="0" value="shu" type="java.lang.String"></constructor-arg>
        <constructor-arg index="1" value="18" type="int"></constructor-arg>
    </bean>

</beans>
  1. effect
    Insert picture description here

2. Inject through the attribute's setter method

  • The setter method has two kinds of injections, generally the first one is intuitive
  1. beans1.xml
    Insert picture description here
  2. effect
    Insert picture description here

3. Inject through the p namespace [understand]

  • Classes using this method must provide get/set methods for the properties, otherwise an error will be reported
  1. beans2.xml
    Insert picture description here
  2. effect
    Insert picture description here

1.2 SpEL expression [understand]

  • SpEL: Spring expression
  • Perform unified programming on <property>, and all contents use value.
  • <property name="" value="#{Expression}">
    #{123}, #{'jack'}: number, string
    #{beanId}: another bean reference
    #{beanId.propName}: manipulation data
    #{beanId.toString()}: Execution method
    #{T(Class) .Field |Method}: Static method or field

Demo

  1. Provide get/set method of Address property, rewrite toString
    Insert picture description here
  2. Provide get/set method of Customer property, rewrite toString (toString does not need to contain address)
    Insert picture description here
  3. beans3.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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--SpEL:spring表达式
      <property name="" value="#{表达式}">
          #{123}、#{'jack'} : 数字、字符串
          #{beanId}	:另一个bean引用
          #{beanId.propName}	:操作数据
          #{beanId.toString()}	:执行方法
          #{T(类).字段|方法}	:静态方法或字段
    -->
    <!--创建一个地址对象-->
    <bean class="com.it.model.Address" id="address">
        <property name="name" value="北京"></property>
    </bean>

    <bean class="com.it.model.Customer" id="customer">
        <!--<property name="name" value="shu"></property>-->
        <!--这样写的好处是能调用方法-->
        <property name="name" value="#{
     
     'shu'.toUpperCase()}"></property>

        <!--还可以将address.name 地址名赋值给客户名(操作数据的一种写法)-->
        <!--<property name="name" value="#{address.name}"></property>-->

        <!--<property name="pi" value="3.14"></property>-->
        <!--调用静态方法 Math.PI-->
        <property name="pi" value="#{T(java.lang.Math).PI}"></property>

        <!--一个对象引用另外一个对象的两种写法:-->
        <!--1.ref引用-->
        <!--<property name="address" ref="address"></property>-->
        <!--2.使用spel 在Customer中引用了另外一个(Address)bean-->
        <property name="address" value="#{address}"></property>

    </bean>

</beans>
  1. effect
    Insert picture description here

1.3 Collection injection

  • The injection of the collection is to add subtags to <property>
  • Array: <array>
    List: <list>
    Set: <set>
    Map: <map>, map stores k/v key-value pairs, use <entry> to describe
    Properties: <props> <prop key=" "></prop > </props>
  • Common data: <value>
  • Reference data: <ref>

List, Set, Map, Properties, Array

  1. Write a programmer class to provide the following get/set methods for collections and arrays
    Insert picture description here
  2. beans4.xml configuration
<?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集合注入-->
    <bean class="com.it.model.Programmer" id="programmer">
        <property name="cars">
            <!--list集合的注入-->
            <list>
                <value>奔驰</value>
                <value>宝马</value>
                <value>ofo</value>
            </list>
        </property>

        <property name="pats">
            <!--set集合的注入-->
            <set>
                <value>大黄</value>
                <value>哈士奇</value>
                <value>蓝猫</value>
            </set>
        </property>

        <property name="infos">
            <!--map集合的注入-->
            <map>
                <entry key="name" value="shu"></entry>
                <entry key="password" value="123"></entry>
                <entry key="age" value="18"></entry>
            </map>
        </property>

        <property name="mysqlInfos">
            <!--properties的注入-->
            <props>
                <prop key="url">mysql:jdbc://localhost:3306/spring_day02</prop>
                <prop key="username">root</prop>
                <prop key="password">root</prop>
            </props>
        </property>

        <property name="members">
            <!--数组注入-->
            <array>
                <value>father</value>
                <value>mother</value>
                <value>sister</value>
            </array>
        </property>
    </bean>

</beans>
  1. effect
    Insert picture description here

1.4 Annotation injection

  • Annotation: is a class using @ annotation name Under
    development: using annotations to replace the xml configuration file

@Component use case

  • @component取代:<bean class="">
  1. Add a @Component on UserServiceImpl
    Insert picture description here
  2. Bean5.xml configuration, using this method requires opening annotations and configuring the location of annotation scanning
    Insert picture description here
  3. Use and effect (successfully injected value)
    Insert picture description here

@Component("id") Use Case

  • @Component(“id”)取代: <bean id="" class="">
  1. Add a @Component("userService") on UserServiceImpl
    Insert picture description here
  2. The beans5.xml configuration is the same as above, just open the annotation and configure the annotation position
  3. Use and effect (value injection is also successful)
    Insert picture description here

Web-service-dao configuration without annotations

  1. Dao implementation class (simple to use, no database for the time being)
    Insert picture description here
  2. Service implementation class (userDao is assigned through spring)
    Insert picture description here
  3. The use of web-action (userService is assigned via spring)
    Insert picture description here
  4. beans6.xml configuration
    Insert picture description here
  5. Use and effect
    Insert picture description here

Annotated web-service-dao configuration

  • For web development, provide 3 @Component annotation derivative annotations (the same function)
    instead of

    <bean class=""> @Repository("name"): dao layer @Service("name"): service layer @Controller("name") : Web layer

    @Autowired: automatically inject according to the type
    @Qualifier("name"): specify the id name of the automatic injection
    @Resource(name="name"): the combination of @Autowired and @Qualifier("name")


    @Scope(" prototype”): multiple cases, the default is singleton


    @ PostConstruct custom initialization
    @ PreDestroy custom destruction
  1. Use @Repository annotation on dao implementation class
    Insert picture description here
  2. Use @Service annotation on the service implementation class, and use @Autowired on userDao to automatically inject according to type
    Insert picture description here
  3. Use @Controller annotation on UserAction to indicate the web layer
    Insert picture description here
  4. For beans7.xml configuration, just turn on the annotation and configure the scan annotation
    Insert picture description here
  5. Same effect, easy and fast to use
    Insert picture description here
  6. Use of @Qualifier("name") (specify the id name to be automatically injected) In
    UserAction: In
    Insert picture description hereUserServiceImpl:
    Insert picture description here
  7. Use of @Resource(name="name")
    Insert picture description here
  8. The use of @Scope("prototype") (multiple cases, the default is singleton) is
    not configured, the default is single column, the UserAction class object is obtained from the spring container,
    Insert picture description here
    after the same configuration, there are multiple cases, each time Will return a new object, which is
    Insert picture description here
    Insert picture description here
    equivalent to the single column and multiple instances previously configured in beans.xml
    Insert picture description here
  9. The use of @ PostConstruct custom initialization and @ PreDestroy custom destruction is configured
    in the implementation class of UserDao:
    Insert picture description here
    pay attention to the use of context to call the method of closing the container to execute the custom destruction methodInsert picture description here

Guess you like

Origin blog.csdn.net/qq_43414199/article/details/108514550