Usage of [Spring MVC] @Configuration

Source: https://www.cnblogs.com/duanxz/p/7493276.html

From Spring 3.0, @ Configuration is used to define Configuration classes and replace xml Configuration files. The annotated classes contain one or more methods annotated by @ bean. These methods will be scanned by AnnotationConfigApplicationContext or AnnotationConfigWebApplicationContext classes, and used to build bean definitions and initialize Spring containers.

Note: the Configuration class of @ Configuration annotation has the following requirements:

@Configuration cannot be of final type;
@Configuration cannot be an anonymous class;
Nested configuration must be a static class.
1, Load spring with @ Configuration
1.1, @ Configuration configures spring and starts the spring container
1.2 @ Configuration start container + @ Bean register Bean
1.3 @ Configuration startup container + @ Component registration Bean
1.4. Two methods of registering AppContext class with annotationconfidapplicationcontext
1.5. Configure Web application (annotationconfigpplicationcontext is configured in web.xml)

2, Combining multiple configuration classes
2.1. Introduce spring's xml configuration file into @ configuration
2.2. Introduce other annotation configurations in @ configuration
2.3 @ Configuration nesting (the nested Configuration must be a static class)
3, @ EnableXXX comments
4, @ Profile logical group configuration
5, Use external variables

@Configuration load Spring method

@Configuration annotation a class configuration application context

Annotate a class with @ configuration, which is equivalent to the application context (xml) of Spring container
Configuration class

package test;

import org.springframework.context.annotation.Configuration;

@Configuration
public class BeansContainer {
    public BeansContainer(){
        System.out.println("start-up spring container");
    }
    
}

Equivalent to the xml application context

<?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:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">


</beans>

test

package test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

public class test {
    public static void main(String[] args){
        AbstractApplicationContext context
                = new AnnotationConfigApplicationContext(BeansContainer.class);
    }
}

Result

@Configuration starts the container + @ Bean register the Bean, and manages the Bean's life cycle under @ Bean

@Bean is labeled on the method (the method that returns an instance), which is equivalent to that in spring's xml configuration file. Its function is to register bean objects

Class bean:

package test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;


@Configuration
public class BeansContainer {
    public BeansContainer(){
        System.out.println("start-up spring container");
    }

    @Bean("person")
    @Scope("prototype")
    public Person createPerson(){
        return new Person();
    }

    
}

Configuration class

package test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;


@Configuration
public class BeansContainer {
    public BeansContainer(){
        System.out.println("start-up spring container");
    }

    @Bean("person")
    @Scope("prototype")
    public Person createPerson(){
        return new Person();
    }

    
}

test

package test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

public class test {
    public static void main(String[] args){
        AbstractApplicationContext context
                = new AnnotationConfigApplicationContext(BeansContainer.class);

        Person person = context.getBean("person",Person.class);
    }
}

Result

Note:
(1) The @ bean annotation returns the instance method. If the bean name is not specified through @ bean, the default is the same as the annotated method name;
(2) The default scope of @ Bean annotation is singleton scope, which can be set as prototype scope through @ Scope("prototype");
(3) , since @ bean is used to register bean objects, annotations such as @ Component, @ Controller, @ Service, @ Ripository can be used to register beans. Of course, @ ComponentScan annotation needs to be configured for automatic scanning.

@Managing bean life cycle under bean

Java based configuration can be used to manage the life cycle of a bean. @Bean supports two attributes, initMethod and destroyMethod, which can be used to define lifecycle methods. When a bean is instantiated or about to be destroyed, the container can call a lifecycle method. A lifecycle method is also called a callback method because it will be called by the container. Beans registered with @ bean annotation also support the standard @ PostConstruct and @ PreDestroy annotations specified in JSR-250. If you are using XML methods to define beans, you should use bean elements to define life cycle callback methods. The following code shows the methods that are commonly used in XML configurations to define callbacks using bean elements.

Class bean

package test;

public class Person {
    private String name;
    public Person(){
        System.out.println("Establish Person object");
        System.out.println(this);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void init(){
        System.out.println("this is init()");
    }
    
    public void destroy(){
        System.out.println("this is destroy");
    }
    
}

Configuration class

package test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;


@Configuration
public class BeansContainer {
    public BeansContainer(){
        System.out.println("start-up spring container");
    }

    @Bean(name = "person",initMethod = "init",destroyMethod = "destroy")
    @Scope("prototype")
    public Person createPerson(){
        return new Person();
    }

    
}

test

package test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

public class test {
    public static void main(String[] args){
        AbstractApplicationContext context
                = new AnnotationConfigApplicationContext(BeansContainer.class);

        Person person = context.getBean("person",Person.class);

        Person person2 = context.getBean("person",Person.class);


    }
}

Result

Analysis:

1 in result: indicates initMethod is in effect

2 in the result: indicates that @ Scope("prototype") is in effect

@Configuration start container + @ Component register Bean

Class bean:

package test;

import org.springframework.stereotype.Component;

@Component("p")
public class Person {
    private String name;
    public Person(){
        System.out.println("Establish Person object");
        System.out.println(this);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void init(){
        System.out.println("this is init()");
    }
    
    public void destroy(){
        System.out.println("this is destroy");
    }
    
}

Configuration class

package test;

import org.springframework.context.annotation.*;


@Configuration
@ComponentScan(basePackages = "test")
public class BeansContainer {
    public BeansContainer(){
        System.out.println("start-up spring container");
    }

    /**
    @Bean(name = "person",initMethod = "init",destroyMethod = "destroy")
    @Scope("prototype")
    public Person createPerson(){
        return new Person();
    }*/

    
}

test

package test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

public class test {
    public static void main(String[] args){
        AbstractApplicationContext context
                = new AnnotationConfigApplicationContext(BeansContainer.class);

        Person person = context.getBean("p",Person.class);

    }
}

@Component ("bean name") specifies the bean name for easy access

Two methods of registering AppContext class with annotationconfigpplicationcontext

The configuration class is registered by passing it to the annotationconfigpplicationcontext constructor

	// @For the spring container loading method of Configuration annotation, replace ClassPathXmlApplicationContext with annotationconfigpplicationcontext
    ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

	//Get bean
	TestBean tb = (TestBean) context.getBean("testBean");
	tb.sayHello();

The register method of annotationconfigpplicationcontext passes in the configuration class to register the configuration class

public static void main(String[] args) {
  ApplicationContext ctx = new AnnotationConfigApplicationContext();
  ctx.register(AppContext.class)
}
Configure Web application (annotationconfigpplicationcontext is configured in web.xml)

In the past, you used to use the XMLWebApplicationContext context to configure Spring Web applications, that is, to specify the path of the external XML context file in the Web deployment descriptor file web.xml. XMLWebApplicationContext is the default context class used by Web applications. The following code describes the elements in web.xml that point to the external XML context file that will be loaded by the ContextLoaderListener listener class.

<web-app>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <servlet>
    <servlet-name>sampleServlet</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    </servlet>

...
</web-app>

Now, you want to change the above code in web.xml to use the annotationconfidapplicationcontext class. Remember, XmlWebApplicationContext is Spring's default context implementation for Web applications, so you never have to explicitly specify this context class in your web.xml file. Now, you will use Java based configuration, so when you configure a Web application, you need to specify the annotationconfigpplicationcontext class in the web.xml file. The above code will be modified as follows:

<web-app>
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.
            support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            demo.AppContext
        </param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <servlet>
    <servlet-name>sampleServlet</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.
            support.AnnotationConfigWebApplicationContext
        </param-value>
    </init-param>
    </servlet>

...
</web-app>

The above modified web.xml now defines the AnnotationConfigWebApplicationContext context class as part of the context parameters and servlet elements. The context configuration location now points to the AppContext configuration class. It's very simple. The next section demonstrates the implementation of the bean's lifecycle callback and scope.

@Configuration summary

@Configuration is equivalent to < beans > < beans >
@Bean is equivalent to < bean > < / bean >
@Component scan is equivalent to < context: component scan base package = "com. Dxz. Demo" / >

Combining multiple configuration classes

Introducing spring's xml configuration file into @ configuration

Configuration class

package test;

import org.springframework.context.annotation.*;
import test2.Config;

@Configuration
@ImportResource("classpath:xspringmvc-servlet.xml")
@ComponentScan(basePackages = "test")
public class BeansContainer {
    public BeansContainer(){
        System.out.println("start-up spring container");
    }
}

xml file

<?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 https://www.springframework.org/schema/context/spring-context.xsd">


    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- One of the supported attributes, the maximum supported file size, in bytes -->
        <property name="maxUploadSize" value="100000"/>
    </bean>
    <bean 
</beans>

Unfortunately, when I want to add the above beans, I will report an error, which may be related to dependency. It is OK to import my own beans.

Introduce other annotation configurations in @ configuration

Configuration class

package test;

import org.springframework.context.annotation.*;
import test2.Config;


@Configuration
@Import(Config.class)
@ComponentScan(basePackages = "test")
public class BeansContainer {
    public BeansContainer(){
        System.out.println("start-up spring container");
    }

}

package test2;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {
    public Config(){
        System.out.println("start-up Config container");
    }
    @Bean
    public Student student(){
        return new Student();
    }


}

@Configuration nesting (nested configuration must be a static class)

The purpose of combining multiple configuration classes is to configure the nested configuration classes. But notice that the inner class must be a static class

package test;

import org.springframework.context.annotation.*;
import test2.Config;


@Configuration
@ComponentScan(basePackages = "test")
public class BeansContainer {
    public BeansContainer(){
        System.out.println("start-up spring container");
    }

    @Configuration
    static class innerBeansContainer{
        public innerBeansContainer(){
            System.out.println("start-up BeansContainer container");
        }
        @Bean
        public boss boss(){
            return new boss();
        }

    }
}

Published 53 original articles, won praise 4, visited 4748
Private letter follow

Tags: Spring xml JDBC encoding

Posted on Thu, 13 Feb 2020 02:01:09 -0800 by rach123