Spring4.0 study notes (2)

automatic assembly

  • The Spring IOC container can autowire beans. All you need to do is specify the autowired mode in the autowire attribute of
  • byType (autowired by type): If there are multiple beans in the IOC container that are of the same type as the target bean. In this case, Spring
    will not be able to determine which bean is the most suitable for this property, so autowiring cannot be performed.
  • byName (autowired by name): The name of the target bean and the property name must be set exactly the same.
  • constructor (autowiring by constructor): When there are multiple constructors in the Bean, this autowiring method will be complicated. Not recommended
bean-autowire.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">

    <bean id="address" class="com.anqi.autowire.Address" 
        p:city="Taiyuan" p:street="HonggouStreet"></bean>

    <bean id="car" class="com.anqi.autowire.Car" p:brand="ChangAn"
        p:price="250000"></bean>

    <!-- 
        可以使用 autowire 属性指定自动装配的方式
        byName 根据 bean 的名字和当前 bean 的 setter 风格的属性名进行自动装配, 若有匹配的则进行自动装配
        byType 根据 bean 的类型和当前 bean 的类型进行装配 若 IOC 容器里有1个以上的类型匹配的bean,则抛异常
     -->
    <bean id="person" class="com.anqi.autowire.Person" 
        p:name="AnQi" p:address-ref="address" autowire="byName"> </bean>

    <bean id="person2" class="com.anqi.autowire.Person" 
        p:name="AnQi2" p:address-ref="address" autowire="byType"> </bean>   
</beans>
Person.java
package com.anqi.autowire;

public class Person {

    private String name;
    private Address address;
    private Car car;
    //...setter 、getter、toString

}
Address.java
package com.anqi.autowire;

public class Address {

    private String city;
    private String street;
    //...setteri 、getter、toString
}
Car.java
package com.anqi.autowire;

public class Car {

    private String brand;
    private double price;
    //...setteri 、getter、toString
}

Main.java

package com.anqi.autowire;

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

public class Main {
    public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-autowire.xml");

        Person p = (Person) ctx.getBean("person");
        System.out.println(p);
        //Person [name=AnQi, address=Address [city=Taiyuan, street=HonggouStreet], 
        //car=Car [brand=ChangAn, price=250000.0]]

        p = (Person) ctx.getBean("person2");
        System.out.println(p);
        //Person [name=AnQi2, address=Address [city=Taiyuan, street=HonggouStreet], 
        //car=Car [brand=ChangAn, price=250000.0]]
    }
}

relationship between beans

inheritance relationship

  • Spring allows the configuration of inherited beans, and the inherited bean is called the parent bean . The bean that inherits the parent bean is called the child bean
  • The child bean inherits the configuration from the parent bean, including the attribute configuration of the bean
  • Child beans can also override configuration inherited from parent beans
  • The parent bean can be used as a configuration template or as a bean instance. If you only want to use the parent bean as a template, you can set the abstract property to true, so that Spring will not instantiate this bean
  • Not all properties in an element will be inherited. For example: autowire, abstract etc.
  • You can also ignore the class attribute of the parent bean and let the child bean specify its own class and share the same attribute configuration. But at this time abstract must be set to true

dependencies

  • Spring allows users to set the pre-dependent beans of the bean through the depends-on attribute , and the pre-dependent beans will be created before the instantiation of this bean
  • If the prefix depends on multiple beans, you can configure the name of the bean by comma, space or
<?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">

    <!-- 抽象 bean : bean 的 abstract 属性为 true 的bean, 这样的 bean 不能被 IOC 容器实例化
        只能被用来继承配置  -->
    <!--<bean id="address" class="com.anqi.autowire.Address" p:city="Taiyuan"
        p:street="Wulongkou"></bean> -->

    <!-- 若某父类 bean 的 class 属性没有被指定, 则该 bean 必须是一个抽象 bean -->    
    <bean id="address"  p:city="Taiyuan"
        p:street="Wulongkou" abstract="true"></bean>    

    <!-- bean 配置的继承 : 使用 bean 的 parent 属性指定继承哪个 bean 的配置 -->
    <bean id="address2" class="com.anqi.autowire.Address" p:city="Xinzhou" 
        parent="address"></bean>

    <bean id="car" class="com.anqi.autowire.Car" p:brand="Benci" 
        p:price="290000"></bean>

    <!-- 要求在配置 Person 时, 必须有一个关联的 car,换句话说 Person 这个 bean 依赖于 Car 的 bean -->
    <bean id="person" class="com.anqi.autowire.Person" p:name="安琪" 
        p:address-ref="address2" depends-on="car" p:car-ref="car"></bean>
</beans>

Bean scope

  • In Spring, a bean's scope can be set in the element's scope attribute.
  • By default, Spring only creates a unique instance of each bean declared in the IOC container, which is shared across the entire IOC container : all subsequent getBean() calls and bean references will return this unique bean instance . This scope is called singleton and it is the default scope for all beans
    write picture description here
    <!-- 
        使用 bean 的 scope 属性来配置 bean 的作用域
        singleton : 默认值, 容器的初始时创建 bean 对象, 在整个容器的生命周期只能创建
                    这一个 bean, 单例的。无参构造器在容器启动时执行。
        prototype : 原型的, 容器初始化时不创建 bean 的实例, 而在每次请求时都创建一个
                    新的 bean 实例, 并返回
     -->
    <bean id="car" class="com.anqi.autowire.Car">
        <property name="brand" value="fute"></property>
        <property name="price" value="2500000"></property>
    </bean>

    <bean id="car2" class="com.anqi.autowire.Car" scope="prototype">
        <property name="brand" value="fute2"></property>
        <property name="price" value="25000002"></property>
    </bean>
    public static void main(String[] args) {
        ApplicationContext ctx = 
            new ClassPathXmlApplicationContext("bean-scope.xml");

        Car car = (Car) ctx.getBean("car");
        Car car_ = (Car) ctx.getBean("car");

        System.out.println(car == car_);
        //Constructor.... 不创建对象也会在 ioc 容器启动时自己执行
        //true

        Car car2 = (Car) ctx.getBean("car2");
        Car car3 = (Car) ctx.getBean("car2");
        System.out.println(car2 == car3);
        //Constructor.... 创建对象时调用
        //false
    }

Using an external properties file

  • When configuring beans in configuration files, sometimes it is necessary to mix system deployment details (eg file path, data source configuration information, etc. ) into the bean configuration. These deployment details actually need to be separated from the bean configuration.
  • Spring provides a BeanFactory post-processor for PropertyPlaceholderConfigurer, which allows users to move parts of the bean configuration out to the properties file. Variables of the form ${var} can be used in the bean configuration file, and the PropertyPlaceholderConfigurer from the properties file Load properties in and use those properties to replace variables.
  • Spring also allows the use of ${propName} in property files to enable mutual references between properties

    Example –> Spring configures c3p0 by importing external properties

    Ready to work

    import
    c3p0-0.9.5.2.jar
    mchange-commons-java-0.2.11.jar
    mysqljdbc.jar
    using context namespace

external properties file

user=root
password=1995
driverclass=com.mysql.jdbc.Driver
jdbcurl=jdbc:mysql:///db_javaee
<?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-4.0.xsd">

    <!-- 使用 context 命名空间, 导入属性文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="root"></property>
        <property name="password" value="1995"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///db_javaee"></property> -->

     <!-- 
        准备工作-导入:
            c3p0-0.9.5.2.jar
            mchange-commons-java-0.2.11.jar
            mysqljdbc.jar
        这样的优势是:项目很大的时候,bean 很多,若要修改数据库等配置信息,或者修改数据库
            寻找到这个 bean 花费大量时间, 若采取导入属性文件的方式, 我们直接
            修改 db.properties 更为方便
        除了这些属性, 还有最大连接数等属性可供设置      
      -->
     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
        <!-- 使用外部化属性文件的属性 -->
        <property name="user" value="${user}"></property>
        <property name="password" value="${password}"></property>
        <property name="driverClass" value="${driverclass}"></property>
        <property name="jdbcUrl" value="${jdbcurl}"></property>
     </bean>
</beans>
public class Main {
    public static void main(String[] args) throws SQLException {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-properties.xml");

        DataSource dataSource = (DataSource) ctx.getBean("dataSource");
        System.out.println(dataSource.getConnection());
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325682528&siteId=291194637