[Spring practice series] (15) use Spring Java-based configuration

Source: Internet
Author: User

[Spring practice series] (15) use Spring Java-based configuration
Not all developers like to use XML, so Spring3.0 has prepared something special for these developers. You can use pure Java code to configure Spring applications without using XML. Java-based configuration has some skills not available in XML configuration.1. Create a Java-based configurationEven if Spring Java configuration allows us to write most Spring configurations without using XML, we still need a very small amount of XML to enable Java configuration.


  
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 http://www.springframework.org/schema/context/spring-context.xsd"> We already know Is how to automatically register those beans labeled using a certain constructor type annotation. However, it automatically loads the classes marked with the @ Configuration annotation. In this example, the base-package attribute tells Spring to search for all classes marked with the @ Configuration annotation in the com. sjf. bean package.   2. Define a configuration class  In Spring-based XML configuration, the root element of the XML configuration comes from the Spring Bean namespace. Element. In Java-based Configuration, the @ Configuration annotation Java class is used to replace Element.
package com.sjf.bean;
import org.springframework.context.annotation.Configuration;/*** Java-based configuration * @author sjf0115 * */@Configurationpublic class SpringConfig { // Bean declaration methods }   @ Configuration annotation is used as an identifier to inform Spring that this class will contain one or more Spring Bean definitions. The definitions of these beans are marked by @ Bean annotations.  3. Declare a simple class  We use @ Bean annotation to annotate a method to define studentBean Bean:
package com.sjf.bean;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/*** Java-based configuration * @author sjf0115 * */@Configurationpublic class SpringConfig { // Bean declaration methods @Bean public Student studentBean(){ return new Student(); }}   This simple method is Java configuration, which is equivalent to Element:
 
@ Bean informs Spring that this method will return an object, which should be registered as a Bean in the Spring application context. The method name is the Bean ID. All the logic implemented in this method is essentially to create a Bean. In the preceding example, this method is created and a Student instance object is returned. This object is registered as a Bean whose ID is studentBean in the Spring application context.  Advantages:

In XML configuration, Bean types and IDs are expressed by Spring attributes. The disadvantage of Spring identifiers is that they cannot be checked by the compiler. There is no String attribute in Spring-based Java configuration. Bean IDs and types are considered part of the method signature. The actual creation of Bean is defined in the method body. Because they are all Java code, we can perform a compiler check to ensure that the Bean type is valid and the Bean ID is unique.
  4. Use Spring Java-based cooperation for Injection  For previous constructor injection methods, you only need to pass the numbers directly into the constructor when using Java Configuration:
@Bean
public Student studentBean(){ return new Student("yoona",24);}   Using Java configurations to define beans is the same as using Java to write class instantiation code. Let's take a look at how setter injection is implemented in Java configuration?
@Bean
public Student studentBean(){ Student stu = new Student(); stu.setName("yoona"); stu.setAge(24); return stu;}   So the Bean Assembly references another Bean? First, create a Bean to be referenced:
@Bean
public School schoolBean(){ School school = new School();School. setName ("Xi'an University of electronic science and technology ");School. setLocation ("Xi'an "); return school;} Now let's take a look at how to reference a Bean. We use the constructor to assemble the Bean above:
@Bean
public Student yoonaStudent(){ return new Student(schoolBean());}   Note:

In Spring Java configuration, referencing a Bean by declaring a method does not mean calling this method. In this case, each time schoolBean () is called, a new instance of the Bean will be obtained. By using the @ Bean annotation to mark the schoolBean () method, we will tell Spring that we want the Bean defined by this method to be registered in the Spring application context. Therefore, when other Bean declaration methods use this method, Spring will intercept the call of this method and try to find the Bean in the application context, instead of letting the method create a new instance.
  5. Run  Once you configure the class definition, you can load and provide them using AnnotationConfigApplicationContext as follows:
package com.sjf.bean;
import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Test { private static ApplicationContext context; public static void main(String[] args){ context = new AnnotationConfigApplicationContext(SpringConfig.class); Student student = (Student)context.getBean("yoonaStudent"); student.setName("yoona"); student.setAge(24); System.out.println(student.toString()); }}  

Reference: Spring practice

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.