directory

  • 1. The basic
  • 2. Xml-based configuration of IOC
  • 3. Annotations based configuration of IOC
  • 4. Concepts related to AOP
  • 6. The spring into the order
  • 7. Message monitoring mechanism
  • 8. Behavior of things control and dissemination
  • 9. The Spring source code
  • 10. The Spring lifecycle

1. Application. XML configuration


      
<! Beans have been added with a number of constraints, which are URL-like codes that restrict which tags can be used in the.xml file.
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

    <! -- Enable annotation scan -->
    <context:component-scan base-package="Things com. Qunar."></context:component-scan>
    <! -- Register user class -->
    <bean name="user" class=Introduction to "com. Qunar. Spring. Pojo. User"></bean>

    <! Write the database configuration information in a separate file, compile and modify the database configuration content to let Spring know the location of the jdbc.properties file.
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <! DataSource = 'DataSource';
    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <! --set injection provides database connection information -->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="${jdbc.maxActive}" />

    </bean>

    <! --SqlSessionFactory-->
    <! SqlSessionFactoryBean = SqlSessionFactoryBean = SqlSessionFactory;
    <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <! DataSource = dataSource; dataSource = dataSource;
        <property name="dataSource" ref="myDataSource"/>
        <! -- Mybatis configLocation property is of the Resource type, and is assigned to value, specifying the path of the file, using classpath: indicating the location of the file -->
        <property name="configLocation" value="classpath:mybatis.xml"/>
    </bean>


    <! MapperScannerConfigurer calls getMapper() internally to generate proxy objects for each DAO interface.
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <! Select * from SqlSessionFactory;
        <property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"/>

        <! MapperScannerConfigurer scans all the interfaces in the package and executes the getMapper() method once for each interface. The dao object is put into spring's container. The default dao object name is lowercase.
        <property name="basePackage" value="com.qunar"/>

        <! -- Multiple packages -->
        <! --<property name="basePackage" value="com.md.dao,com.md.dao2"/>-->
    </bean>
</beans>
Copy the code

2. Bean tags

(1) Function: Configure objects to be created by Spring

By default, an object is created using the no-argument constructor, and without it the creation fails

(2) Attributes:

Id: Gives the object a unique identity in the container. Used to get objects.

Class: Specifies the fully qualified class name of the class. Used for reflection to create objects. The no-argument constructor is invoked by default.

Scope: Specifies the scope of the object.

  • Singleton: Default, singleton.
  • Prototype: Multiple examples.
  • Request: In a WEB project,Spring creates an object of a Bean and stores the object into the Request domain.
  • Session: In a WEB project,Spring creates an object of a Bean and stores the object into the Session domain.
  • Global Session: Applied in a Portlet environment in a WEB project. A globalSession is equivalent to a session if there is no Portlet environment.

Init-method: Specifies the name of the initialization method in the class.

Destroy-method: specifies the name of the destroy-method in the class.

3. Two ways to instantiate beans

The first way: use the default no-argument constructor

<! By default, it creates class objects based on the default no-argument constructor. If there is no default no-argument constructor in the bean, the creation will fail. -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"/>
Copy the code

Second way: use the static methods of the factory class

Public class StaticFactory {public static IAccountService createAccountService(){return new  AccountServiceImpl(); }}<! -- This method is: Create an object using createAccountService, a static method in the StaticFactory class, and store it in the spring container id attribute: specifies the id of the bean used to get the class attribute from the container: specifies the fully qualified class name of the StaticFactory Factory-method property: specifies the static method of the production object -->
<bean id="accountService"
class="com.itheima.factory.StaticFactory"
factory-method="createAccountService"></bean>
Copy the code

Third way: use instance object methods

Public class InstanceFactory {public IAccountService; / / Public class InstanceFactory {public IAccountService; / / Public class InstanceFactory {public IAccountService createAccountService(){ return new AccountServiceImpl(); }}<! This is done by handing over the creation of the factory to Spring. Then use the factory bean to call the inside method factory-bean property, which specifies the ID of the instance factory bean. Factory-method property: Used to specify the method by which the object is created in the instance factory. -->
<bean id="instancFactory" class="com.itheima.factory.InstanceFactory"></bean>
<bean id="accountService"
factory-bean="instancFactory"
factory-method="createAccountService"></bean>
Copy the code

Spring dependency injection

Inject initial values for bean object properties in the Spring container

The first way: constructor injection

<! Using constructors to pass values to attributes in a service requires that the class provide a constructor for a list of parameters. Involved tags: constructor-arg attribute: Index: specifies the index position of the parameter in the constructor argument list type: specifies the data type of the parameter in the constructor name: specifies the name of the parameter in the constructor ======= Ref: It can assign values to other bean types, that is, beans configured in the configuration file -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<constructor-arg name="name" value="Zhang"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<bean id="now" class="java.util.Date"></bean>
Copy the code

The second way: use the set method for injection

<! Pass values to properties in the bean via config file: Ref: Assign attributes to other bean types. Value: Assign attributes to basic data types and string types. In practical development, this method is often used. -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="name" value="test"></property>
<property name="age" value="21"></property>
<property name="birthday" ref="now"></property>
</bean>
<bean id="now" class="java.util.Date"></bean>
Copy the code

5. Collection injection

<! -- insert props, props, props, props, props, props, props, props, props, props
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<! Tags can be used interchangeably as long as the structure is the same.
<! Insert data into array -->
<property name="myStrs">
	<set>
		<value>AAA</value>
		<value>BBB</value>
		<value>CCC</value>
	</set>
</property>
<! Select * from list; select * from list;
<property name="myList">
	<array>
		<value>AAA</value>
		<value>BBB</value>
		<value>CCC</value>
	</array>
</property>
<! Select * from set;
<property name="mySet">
	<list>
		<value>AAA</value>
		<value>BBB</value>
		<value>CCC</value>
	</list>
</property>
<! Insert Map data -->
<property name="myMap">
	<props>
		<prop key="testA">aaa</prop>
		<prop key="testB">bbb</prop>
	</props>
</property>
<! Insert properties data -->
<property name="myProps">
	<map>
		<entry key="testA" value="aaa"></entry>
		<entry key="testB"><value>bbb</value></entry>
	</map>
</property>

</bean>
Copy the code

6. The lookup method and replace — method

Spring’s method injection falls into two categories

Lookup method injection: Used to inject methods that return results, that is, can be configured to replace methods that return results. This is commonly known as lookup-method injection.

Replacement method injection: You can implement the replacement of the method body or the return result, which is commonly known as spokes-method injection.

(a) lookup – method

(1) When a singleton depends on multiple instances, it is guaranteed that the multiple instances obtained will not be stored in the Spring container, and each singleton holds multiple instances independently

(2) Enhance the return result of the method

public class Car {

    // used for lookup-method injection
    public Taxi createTaxi(a){
        System.out.println("car");
        Taxi taxi = new Taxi();
        taxi.setTaxiNmae("carCreate");
        return taxi;
    }

    private Taxi taxi;

    public Taxi getTaxi(a) {
        return taxi;
    }
    
    / / setter injection
    public void setTaxi(Taxi taxi) {
        this.taxi = taxi; }}public class Taxi {
    private String taxiNmae;

    public void setTaxiNmae(String taxiNmae) {
        this.taxiNmae = taxiNmae;
    }

    public void say(a) {
        System.out.println("I am a Taxi..."+taxiNmae); }}public class lookupMethodwithreplaceMethod {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("lookupMethodAndRelapceMethod.xml");

        Car car1 = (Car) applicationContext.getBean("car");
        Car car2 = (Car) applicationContext.getBean("car");
        System.out.println("Car:singleton, so car1==car2 should be" + (car1 == car2));

        Taxi taxi1 = car1.getTaxi();
        Taxi taxi2 = car1.getTaxi();
        System.out.println("Taxi: prototype, the Car: the singleton, not to use the lookup - method injection so taix1 = = taxi2 should be" + (taxi1 == taxi2));

        Taxi taxi3 = car1.createTaxi();
        Taxi taxi4 = car1.createTaxi();
        System.out.println("Taxi: prototype, the Car: the singleton, use the lookup - method injection so taix3 = = taxi4 should be"+ (taxi3 == taxi4)); taxi1.say(); taxi3.say(); }}Copy the code
<bean id="taxi" class=Introduction to "com. Qunar. Spring. Pojo. Taxi" scope="prototype"></bean>
    <bean id="car" class=Introduction to "com. Qunar. Spring. Pojo. Car." ">
        <property name="taxi" ref="taxi"></property>
        <lookup-method name="createTaxi" bean="taxi" ></lookup-method>
    </bean>
Copy the code

The output

Car: the singleton, so car1 = = car2 should to true Taxi: prototype, the Car: the singleton, not to use the lookup - method injection so taix1 = = taxi2 should be true Taxi: prototype, the Car: the singleton, use the lookup - method injection so taix3 = = taxi4 should to false I am a Taxi... null I am a Taxi... nullCopy the code

(2) the replace method

Replace the method body and its return value

Note that the enhanced method must implement the MethodReplacer interface

public class OriginalDog {
    public void sayHello(a) {
        System.out.println("Hello,I am a black dog...");
    }

    public void sayHello(String name) {
        System.out.println("Hello,I am a black dog, my name is "+ name); }}public class  ReplaceDog implements MethodReplacer {
    @Override
    public Object reimplement(Object obj, Method method, Object[] args) throws Throwable {
        System.out.println("Hello, I am a white dog...");
        Arrays.stream(args).forEach(str -> System.out.println("Parameters." + str));
        returnobj; }}public class lookupMethodwithreplaceMethod {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("lookupMethodAndRelapceMethod.xml");

        System.out.println("+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +");
        OriginalDog originalDog = (OriginalDog) applicationContext.getBean("originalDog");
        originalDog.sayHello("sssss"); }}Copy the code
<! - = = = = = = = = = = = = = = = = = = = = the replace - injection method attribute = = = = = = = = = = = = = = = = = = = = -- -- >
    <bean id="replaceDog" class=Introduction to "com. Qunar. Spring. Pojo. ReplaceDog"></bean>
    <bean id="originalDog" class=Introduction to "com. Qunar. Spring. Pojo. OriginalDog">
        <replaced-method name="sayHello" replacer="replaceDog">
            <arg-type match="java.lang.String"></arg-type>
        </replaced-method>
    </bean>
Copy the code

The output

Hello, I am a white dog... Parameters: SSSSSCopy the code

7. Spring introduces multiple configuration files

(1) Use the

tag to import additional configuration files

 <import resource="Configuration file 2.xml"></import>
    <bean id="user" class=Introduction to "com. Qunar. Spring. Pojo. User"></bean>
Copy the code

(2) Pass multiple configuration files directly into ApplictionContext

 ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("Configuration file 1.xml"."Configuration file 2.xml");
Copy the code

8. Overwriting of spring named beans