Spring Java-based configuration

Source: Internet
Author: User

Javaconfig is a sub-project of spring. It aims to provide bean definition information through Java classes. For a common pojo, you only need to mark the @ configuration annotation, the bean definition information provided by the spring container. Every class method labeled @ bean provides the bean definition information.

Package spring. IOC. autowired; import Org. springframework. context. annotation. bean; import Org. springframework. context. annotation. configuration; import spring. IOC. demo1.car; // define a pojo annotation as the configuration class @ configuration public class configurationuse of the Sping bean {// every class method labeled @ bean provides the definition information of a bean // the bean type is determined by the type of the method return value. car1 corresponds to the bean with ID = car1 in XML @ bean public car car1 () {return new car ();} Public String tostring () {return car1 (). tostring ();}}
<Bean id = "car1" class = "Spring. IOC. demo1.car "Scope =" prototype "P: Brand =" Spring injection-Hongqi 001 "P: color =" Spring injection-purple "P: maxspeed =" 520 "/>
public static void main(String[] args) {                ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");     ConfigurationUse configurationUse = ctx.getBean(ConfigurationUse.class);        System.out.println("@Configuration:" + configurationUse);}

Output: @ configuration: The car is: Spring injection-Hongqi 001, color is: Spring injection-purple, maxspeed is: 520

 

If bean is defined in multiple @ configuration classes, we can also reference the beans defined in different configuration classes:

package spring.ioc.autowired;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;@Configuration(value="configurationTemp")public class ConfigurationTemp {        @Autowired    ConfigurationUse configurationUse;        public String toString(){         return configurationUse.car1().toString();    }}
public static void main(String[] args) {                ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");             ConfigurationTemp configurationTemp = ctx.getBean("configurationTemp",ConfigurationTemp.class);        System.out.println("ConfigurationTemp:" + configurationTemp);}

Output: configurationtemp: The car is: Spring injection-Hongqi 001, color is: Spring injection-purple, maxspeed is: 520

Because the @ configuration annotation class has already been labeled with @ component annotation, any class labeled with @ configuration itself is equivalent to marking @ component.

Return configurationuse. car1 () does not simply execute the method logic in configurationuse, but returns the corresponding car instance from the spring container.

@ Scope ("prototype") ensures that the car bean retrieved from the container is in the latest status every time.

 

Comparison and summarization Based on XML, annotation, and Java

  XML-Based Configuration Annotation-Based Configuration Java-based configuration
Bean Definition Use the <bean> element to define beans in XML, for example, <bean id = "bean1" class = "com.360buy. bean1" In the bean implementation class, define the bean by annotation @ compoent or derivation (@ respository, @ service, @ Controller) In the Java class labeled @ congiguration, the @ bean defines a bean by marking the class method. The method must provide the bean instantiation logic.
Bean name Defined by the ID or name attribute of <bean>

The value attribute is defined by annotation, such:

@ Component (value = "userdao ")

Use the name attribute definition of @ bean, such:

@ Bean (name = "userdao"). The default name is the method name.

Bean Injection Use <property> sub-elements or dynamic attributes of the P namespace. By marking @ autowired in member variables or method entry parameters, automatic injection by type is performed by default. You can also use @ qualifier for name-based injection. Flexible. You can bind the method parameter to bean through @ autowired In the method, or call the @ bean method of the configuration class for injection.
Bean life process call Method You can use the init-method and destroy-method attributes of <bean> to specify the method name of the bean implementation class. You can specify at most one initialization method and destruction method. By marking @ postconstruct and @ predestroy annotations on the target method, you can define any number Use the initmethod or destroymethod of @ bean to specify an initialization or destruction method.
Bean Scope Use the scope attribute of <bean> to specify By marking @ scope ("propotype") in the class definition ") By marking @ scope ("propotype") in bean method definition ")
Bean delayed Initialization It is specified through the lazy-init attribute of <bean>. The default value is default, which is inherited from the default-Lazy-init setting of <beans>. The default value is false.

Specify by marking @ lazy in the class definition, as shown in figure

@ Lazy (true)

Specify by marking @ lazy in bean method definition
Applicable scenarios

1. Bean implementation classes come from third-party class libraries, such as datasource and jdbctemplate. Because annotations cannot be added to classes, it is better to configure them through XML.

2. configurations of namespaces, such as AOP and context, can only be configured based on XML.

Bean implementation classes are developed by the current project. The customer directly uses annotation-based configuration in the Java class.

The advantage of Java-based configuration is that the overall logic of bean initialization can be controlled through code. Therefore, if the logic of bean instantiation is complicated, it is more suitable to use Java-based configuration.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.