Spring Introduction Study Notes (2.08) -- simplify xml configuration with Java config

Source: Internet
Author: User

The spring javaconfig project is outdated and its core functions have been transplanted to the core spring Framework Version 3.0.

Java config is a completely different way of working from other configuration options (via XML or annotation. Java config can be mixed with existing methods. The easiest way to enable Java configuration is to use the xml configuration file, and then spring will handle the rest.

ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("myApplicationContext.xml");

File configuration is as expected:

...<context:annotation-config /><context:component-scan base-package="com.my.base.package" />...


This allows spring to find any classes marked with @ configuration.@ Configuration: Use @ component for Metadata Annotation to get annotation support. For example, you can use the @ autowired annotation for automatic injection. Once the class uses the @ configuration annotation, spring searches for bean definitions in the class. (Bean is defined as a Java method with @ bean annotation .)Any definition helps applicationcontext obtain beanname from the method used to configure it. You can also specify the bean name in the @ bean annotation. Configurations with a bean definition may look like this:

package com.codeproject.jackie.springrecipesnote.springadvancedioc;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class PersonConfiguration {@Bean(name="theArtistFormerlyKnownAsJosh")public Person josh() {Person josh = new Person();josh.setName("Josh");return josh;}}

It is equivalent to the following XML application context definition:

<bean id="josh" class="com.codeproject.jackie.springrecipesnote.springadvancedioc.Person" p:name="Josh" />

You can use the spring application context to access the bean as usual.

public class PersonTest {@Testpublic void testJavaConfig() {ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfiguration.class);Person person = applicationContext.getBean("theArtistFormerlyKnownAsJosh", Person.class);System.out.println(person);}}

Note: spring3.0 has been addedAnnotationConfigApplicationContextThis application context, this generic applicationcontext implementation can not only accept the @ configuration annotation class as the input, but also accept the pure @ component annotation class and the class annotated by the JSR-330 metadata as the input.
To specify the bean ID, you can use the ID attribute of the @ bean annotation.

@Bean(name="theArtistFormerlyKnownAsJosh")public Person josh() {// …}

You can access this bean as follows:

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfiguration.class);Person person = applicationContext.getBean("theArtistFormerlyKnownAsJosh", Person.class);

Although the Code line is 5 times more than the xml configuration, it is easy to parse.
If you want to specify the lifecycle method, you can also choose more. The life cycle method in spring was previously implemented as a callback. It targets initializingbean and disposablebean interfaces, respectively after dependency injection (Public void afterpropertiesset () throws exception) and bean destruction and removal from the context (Public void destroy () throws exception. You can also manually configure the initialization and destruction methods in the XML configuration file using the init-method and destroy-method attributes of the <bean> element. From spring2.5, you can assign initialization (@ postconstruct) and destruction methods (@ predestroy) using JSR-250 annotations ).

In Java config, you can use the initmethod and destroymethod attributes of the @ bean annotation to specify the lifecycle method, or you can call the method yourself.

        @Bean( initMethod = "startLife", destroyMethod = "die")public Person companyLawyer() {Person companyLawyer = new Person();companyLawyer.setName("Alan Crane");return companyLawyer;}


You can also call the initialization method by yourself.

        @Beanpublic Person companyLawyer() {Person companyLawyer = new Person();companyLawyer.setName("Alan Crane");companyLawyer.startLife();return companyLawyer;}

Referencing other beans is also very simple.

@Configurationpublic class PetConfiguration {   @Bean   public Cat cat(){      return new Cat();   }   @Bean   public Person master(){      Person person = new Person() ;      person.setPet( cat() );      return person;   }   // …}

All bean configuration options declared in XML can be defined through Java config.

@ Lazy, @ primary, and @ dependson have the same effect as XML. @ Lazy: the bean is constructed only when the dependency is satisfied or the application context is displayed for access. @ Dependson: specify that the creation of a bean must be completed after the creation of other beans. @ Primary annotation specifies the one with the @ primary annotation returned when there are multiple beans with the same interfaceThis annotation makes little sense if it is accessed by bean name.

Similar to other annotations, annotations are located on the bean configuration method that it applies.

        @Bean @Lazypublic Person companyLawyer() {Person companyLawyer = new Person();companyLawyer.setName("Alan Crane");companyLawyer.startLife();return companyLawyer;}

Bean configuration is often divided into multiple configuration classes, making the configuration easier to maintain and modularized. Spring allows you to import other beans. In XML, use the import element (<import resource = "someotherelement. xml"/> ). In javaconfig, similar functions are implemented by using the @ import annotation at the class level.

@Configuration@Import(BusinessConfiguration.class)public class FamilyConfiguration {// ...}

In this way, the scope of bean defined in businessconfiguration can be introduced. When necessary, you can use the @ autowired or @ value annotation to access these beans. If @ autowired is used to inject applicationcontext, you can obtain access to a bean.

The following is a complete sample code:

Lawfirmconfiguration class

package com.codeproject.jackie.springrecipesnote.springadvancedioc;import java.util.Arrays;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;@Configuration@Import(AttorneyConfiguration.class)public class LawFirmConfiguration {@Value("#{denny}")private Attorney denny;@Value("#{alan}")private Attorney alan;@Value("#{shirley}")private Attorney shirley;@Beanpublic LawFirm bostonLegal() {LawFirm lawFirm = new LawFirm();lawFirm.setLawyers(Arrays.asList(denny, alan, shirley));lawFirm.setLocation("Boston");return lawFirm;}}

Lawfirm class

package com.codeproject.jackie.springrecipesnote.springadvancedioc;import java.util.List;public class LawFirm {private List<Attorney> lawyers;private String location;public LawFirm() {}/** * @return the lawers */public List<Attorney> getLawyers() {return lawyers;}/** * @param lawers *            the lawers to set */public void setLawyers(List<Attorney> lawyers) {this.lawyers = lawyers;}/** * @return the location */public String getLocation() {return location;}/** * @param location *            the location to set */public void setLocation(String location) {this.location = location;}}

Attorneyconfiguration class

package com.codeproject.jackie.springrecipesnote.springadvancedioc;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class AttorneyConfiguration {@Beanpublic Attorney denny() {Attorney attorney = new Attorney();attorney.setName("denny");return attorney;}@Beanpublic Attorney alan() {Attorney attorney = new Attorney();attorney.setName("alan");return attorney;}@Beanpublic Attorney shirley() {Attorney attorney = new Attorney();attorney.setName("shirley");return attorney;}}

Attorney class

package com.codeproject.jackie.springrecipesnote.springadvancedioc;public class Attorney {private String name;public Attorney() {}/** * @return the name */public String getName() {return name;}/** * @param name *            the name to set */public void setName(String name) {this.name = name;}}

Test class lawfirmtest

package com.codeproject.jackie.springrecipesnote.springadvancedioc;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class LawFirmTest {@Testpublic void testJavaConfig() {ApplicationContext applicationContext = new AnnotationConfigApplicationContext(LawFirmConfiguration.class);LawFirm lawFirm = applicationContext.getBean("bostonLegal", LawFirm.class);System.out.println(lawFirm);}}

For simple bean definitions, this function is too powerful.

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.