Summary of common basic points of Spring (1) spring reference, bean dependency injection, obtaining bean container, initializing bean

Spring has been used all the time, but I basically don't read it again after configuring it once. Some basic points will be forgotten. Here is a simple record.

1. The introduction of spring into the javaWeb project

     1. The configuration in the web.xml file is as follows

     <!-- Introduce spring configuration start -->

<context-param>  

      <param-name>contextConfigLocation</param-name>  

       <param-value>classpath:/applicationContext.xml</param-value>

  </context-param> 

<listener>  

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  

   </listener> 

<!-- Introduce spring configuration end -->

     /***-------------------------------------------Dividing line- -------------------------------------------------- --------********/

     2. The applicationContext.xml file configuration (the default is the application-context.xml path is the same as web.xml, if there is any change, it must be configured in web.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:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context 

http://www.springframework.org/schema/context/spring-context-3.0.xsd

"

default-autowire="byName"

>

<description>Spring公共配置</description>

 

<!-- spring placeholder configuration -->

<bean id="propertyConfigurer"  

   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  

<property name="locations">  

       <list>  

           <value>classpath*:jdbc.properties</value>  

       </list>  

      </property>  

</bean> 

 

<!-- Introduce dataSource configuration-->

<import resource="classpath:dataSource.xml"/>

<!-- Introduce transaction management configuration-->

<import resource="classpath:transcation.xml"/>

 

<!-- Enable spring annotation scanning -->

<context:component-scan base-package="com.hutton.client" > 

    <context:exclude-filter expression="org.springframework.stereotype.Controller"  

            type="annotation" /> 

    </context:component-scan>

 

<bean id="testService" class="com.hutton.client.service.impl.TestServiceImpl" >

</bean>

 

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" abstract="false"  

        lazy-init="false" autowire="default" >  

        <property name="dataSource">  

            <ref bean="dataSource" />  

        </property>  

    </bean>

 

<bean id="testDao" class="com.hutton.client.dao.impl.TestDaoImpl" >

</bean>

</beans>

 

The files referenced in applicaContext.xml are configured as follows:

 The content of the jdbc.properties file is

  dbDriver = com.mysql.jdbc.Driver

dburl = jdbc:mysql://localhost:3306/test?useUnicode=true&autoReconnect=true&characterEncoding=UTF-8

userName=***

password=***

 

 The content of the dataSource.xml file is:

 

<?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"

xmlns:jdbc="http://www.springframework.org/schema/jdbc" 

xmlns:tx="http://www.springframework.org/schema/tx" 

xmlns:repository="http://www.springframework.org/schema/data/repository" 

xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation=" 

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 

http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd 

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 

http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">

<description>Data source configuration</description>

 

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="${dbDriver}" />

<property name="url" value="${dburl}" />

<property name="username" value="${userName}" />

<property name="password" value="${password}"/>

</bean>

 

</beans>

 

/****--------------------------------------Dividing line----- --------------------------------------------***/

 

Second, the centralized injection method commonly used in spring

1. Set method injection, the most commonly used method, the format is as above

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" abstract="false"  

        lazy-init="false" autowire="default" >  

        <property name="dataSource">  

            <ref bean="dataSource" />  

        </property>  

    </bean>

2. Constructor injection. This method of injection refers to constructor injection with parameters, for example:

In the XML file, the form of <property> is also not used, but the <constructor-arg> tag is used, and the ref attribute also points to the name attribute of other <bean> tags:

  1. <!--Configure the bean, which is managed by spring after configuration -->  
  2.     <bean name="springAction" class="com.bless.springdemo.action.SpringAction">  
  3.         <!--(2) Create constructor injection, if the main class has a constructor with parameters, you need to add this configuration-->  
  4.         <constructor-arg ref="springDao"></constructor-arg>  
  5.         <constructor-arg ref="user"></constructor-arg>  
  6.     </bean>  
  7.         <bean name="springDao" class="com.bless.springdemo.dao.impl.SpringDaoImpl"></bean>  
  8.          <bean name="user" class="com.bless.springdemo.vo.User"></bean>
To solve the uncertainty of the parameters of the constructor, you may encounter that the two parameters passed in by the constructor are of the same type. In order to distinguish which value should be assigned, you need to do some small processing:
The following is to set the index, which is the parameter position:
  1. <bean name="springAction" class="com.bless.springdemo.action.SpringAction">  
  2.         <constructor-arg index="0" ref="springDao"></constructor-arg>  
  3.         <constructor-arg index="1" ref="user"></constructor-arg>  
  4.     </bean>  
  1. public class SpringAction {  
  2.     //Inject the object springDao  
  3.     private SpringDao springDao;  
  4.     private User user;  
  5.       
  6.     public SpringAction(SpringDao springDao,User user){  
  7.         this.springDao = springDao;  
  8.         this.user = user;  
  9.         System.out.println("The constructor calls springDao and user");  
  10.     }  
  11.           
  12.         public void save(){  
  13.         user.setName("Kaka");  
  14.         springDao.save(user);  
  15.     }  
  16. }  

 

3. Automatic assembly (annotation method)

Spring not only supports the @Autowired annotation defined by itself, but also supports several annotations defined by the JSR-250 specification, which are @Resource, @PostConstruct and @PreDestroy.

  The role of @Resource is equivalent to @Autowired, except that @Autowired is automatically injected according to byType, while @Resource is automatically injected according to byName by default. @Resource has two important attributes, namely name and type. Spring parses the name attribute of the @Resource annotation as the name of the bean, and the type attribute parses it as the type of the bean. So if the name attribute is used, the automatic injection strategy of byName is used, and the automatic injection strategy of byType is used when the type attribute is used. If neither the name nor the type attribute is specified, the strategy will be automatically injected using byName through the reflection mechanism.

  @Resource assembly order

  (1). If both name and type are specified, the only matching bean will be found from the Spring context for assembly, and an exception will be thrown if not found

  (2). If name is specified, look for a bean with a matching name (id) from the context for assembly, and throw an exception if it is not found

  (3) If type is specified, the only bean with matching type is found from the context for assembly, if not found or more than one is found, an exception will be thrown

  (4) If neither name nor type is specified, it will be assembled automatically according to the byName method; if there is no match, it will fall back to a primitive type for matching, and if it matches, it will be automatically assembled;

 

The difference between @Autowired and @Resource:

 

(1) Both @Autowired and @Resource can be used to assemble beans. Both can be written on fields, or on setter methods.

(2) @Autowired is assembled by type by default (this annotation belongs to spring), by default, the dependent object must exist. If you want to allow null values, you can set its required property to false, such as: @Autowired( required=false) , if we want to use name assembly, we can use it in conjunction with the @Qualifier annotation, as follows:

@Autowired()

@Qualifier("baseDao")

private  BaseDao baseDao;

 

(3) @Resource (this annotation belongs to J2EE), the default installation name is used for assembly. The name can be specified by the name attribute. If the name attribute is not specified, when the annotation is written on the field, the field name is used for installation name lookup by default. If the annotation is written on the setter method, the attribute name is used for assembly by default. Assemble by type when no bean matching the name is found. But it should be noted that if the name attribute is specified, it will only be assembled according to the name.

 

@Resource(name="baseDao")

 

private BaseDao baseDao;

 

 4. Automatic assembly (through configuration files)

In the spring configuration file, configure a property .default-autowire="byName" (autowired by name) in the declaration, see the previous configuration for details.

default-autowire="x"

x has 4 options: byName, byType, constructor and autodetect 

(1). byName:

Service.java

public class Service

{

    Source source;

    public void setSource(Source source)

    {

        this.source = source;

    }

}

applicationContext.xml

<beans

   ...

   default-autowire="byName">

    <bean id="source" class="cn.hh.spring.DBCPSource" scope="prototype"/>

    <bean id="service" class="cn.hh.spring.Service" scope="prototype">

    </bean>

</beans>

cn.hh.spring.DBCPSource implements the Source interface

There is no Source attribute for the bean service in the xml, but autowire="byName" is set in the beans, so that the configuration file will automatically

 

Find the bean with bean id="Source" according to the setSource in cn.hh.spring.Service, and then automatically match it, if not found

 

Not to be assembled.

Note: The name of byName is Xxxx of setXxxx in java, which has nothing to do with the spelling of source in the Source source set above.

 

all can be

public class Service

{

    Source source1;

    public void setSource(Source source1)

    {

        this.source1 = source1;

    }

}

(2). byType:

Service.java same as above

applicationContext.xml

<beans

   ...

   default-autowire="byType">

    <bean id="dbcpSource" class="cn.hh.spring.DBCPSource" scope="prototype"/>

    <bean id="service" class="cn.hh.spring.Service" scope="prototype">

    </bean>

</beans>

There is also no setSource configured, autowire is changed to "byType", the configuration file will find a bean that implements the Source interface, here 

 

cn.hh.spring.DBCPSource implements the Source interface, so it is automatically assembled. If it is not found, it will not be assembled.

If two beans in the same configuration file implement the Source interface, an error will be reported.

Type here refers to the type of the parameter in setSource(Source source).

(3). constructor:

Attempts to find one or more beans in the container that match the constructor parameters of the bean to be autowired, and throws an exception if not found

 

(4). autodetect:

First try to use the constructor to autowire, and then use the byType method.

 

/****--------------------------------------Dividing line----- --------------------------------------------***/

 

Three, several common methods to obtain spring containers

    1. Obtaining through beanFactory, this is the most basic way, it is rarely used, but it is not recommended, just do a little bit of understanding

     The specific test classes are as follows:

/**

 * Implementation description of class BeanFactoryTest.java: TODO class implementation description

 * 

 * <pre>

 * Note that the ApplicationContext can automatically recognize and apply beans that implement BeanFactoryPostProcessor deployed on it. This means that it is very convenient to apply the PropertyPlaceholderConfigurer when using the ApplicationContext. For this reason, users who want to use this or other beans, Factory postprocessors, are advised to use ApplicationContext instead of BeanFactroy.

 * </pre>

 * 

 */

public class BeanFactoryTest {

 

    static Logger logger = LoggerFactory.getLogger(BeanFactoryTest.class);

 

    public static void main(String[] args) {

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        Resource res = resolver.getResource("classpath:applicationContext.xml");

        try {

            logger.info("spring configuration file address:{}", res.getURL().toString());

            @SuppressWarnings("deprecation")

            XmlBeanFactory bf = new XmlBeanFactory(res);

 

            // If used in a BeanFactory, the bean factory post-processor must be run manually:

            PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();

            cfg.setLocation(new FileSystemResource("src/main/resources/jdbc.properties"));

            cfg.postProcessBeanFactory(bf);

            logger.info("init BeanFactory.");

 

            TestService service = (TestService) bf.getBean("testService");

            System.out.println("testService bean is ready for use!");

            System.out.println(service.sayHello("lisi"));

        } catch (IOException e) {

            logger.error("Handle exception", e);

        }

 

    }

}

 

2. Save applicationContext during initialization

   Code:

ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");

ac.getBean("beanId");

or

ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

 

Note: This method is suitable for independent applications using the Spring framework, and the program needs to manually initialize Spring through the configuration file. Commonly used methods when testing locally

 

3. Implement the interface ApplicationContextAware

Description: Implement the setApplicationContext(ApplicationContext context) method of this interface and save the ApplicationContext object. Spring's unit test class, AbstractJUnit4SpringContextTests, uses this approach.

When Spring is initialized, it will inject the ApplicationContext object through this method.

 

4. Inherited from the abstract class ApplicationObjectSupport

Description: The abstract class ApplicationObjectSupport provides the getApplicationContext() method, which can easily obtain the ApplicationContext.

When Spring is initialized, it will inject the ApplicationContext object through the setApplicationContext(ApplicationContext context) method of the abstract class

 

5. Inherited from the abstract class WebApplicationObjectSupport

Description: Similar to the above method, call getWebApplicationContext() to get the WebApplicationContext

 

6. Obtain the ApplicationContext object through the tool class provided by Spring

Code:

import org.springframework.web.context.support.WebApplicationContextUtils;

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);

ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);

ac1.getBean("beanId");

ac2.getBean("beanId");

illustrate:

This method is suitable for the B/S system that adopts the Spring framework, obtains the ApplicationContext object through the ServletContext object, and then obtains the required class instance through it.

 

The difference between the above two tools is that the former throws an exception when the acquisition fails, and the latter returns null.

 

7. Does not depend on servlet and does not require injection

WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); 

  wac.getBean(beanID);

 

Note that when the server is started, when the Spring container is initialized, the Spring container cannot be obtained through the following methods, but only at runtime. For details, you can view the source code org.springframework.web.context.ContextLoader

 

/***------------------------------------------------------------ ---- Dividing line---------------------------------------***/

Although spring provides three methods 3, 4, and 5 to inherit or implement corresponding classes or interfaces in common classes to obtain Spring's ApplicationContext objects, it is necessary to pay attention to the common objects that implement these classes or interfaces when using them. The java class must be configured in the Spring configuration file application-context.xml file. Otherwise the obtained ApplicationContext object will be null.

 

/***------------------------------------------------------------ -------Dividing line----------------------------------------- ---------------***/

 

Fourth, the priority of spring initialization beans

Refer to another blog post http://huttoncs.iteye.com/blog/2244285

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326779835&siteId=291194637