Spring Bean Management with Java configuration--Go to

Source: Internet
Author: User
Tags ranges

Overview

It is well known that the Spring framework is a driver of the control inversion (IOC) or Dependency injection (DI) pattern, which is implemented through container-based configuration. In the past, Spring allowed developers to use XML-based configuration to manage bean dependencies by leveraging application context XML files. This file is outside the application and contains definitions for the bean and its dependencies with the application. Although using XML configuration is simple and convenient, there is still another way to define a bean and its dependencies. This approach is also known as Java-based configuration. Unlike XML, Java-based configuration enables you to programmatically manage beans. This can be achieved by using a variety of annotations. This article will demonstrate the Java configuration example and compare it to the traditional XML configuration method. This article demonstrates the basic use of Java-based configuration in the following steps:

    • Understanding @Configuration and @Bean annotations
    • Registering a configuration class with Annotationconfigapplicationcontext
    • Configuring the Web Application
    • Implement bean lifecycle callbacks and scopes

We will use the "Create course" case for an online university. When you create a course, you also create themes or modules, and each topic may have different jobs. So we're going to create three beans, Course, Module, and assignment, respectively. The Course bean will contain a reference to the Bean Module , which contains a Assignment reference to the bean.

Understanding @Configuration and @Bean annotations

In an ideal scenario, you can define the bean in the XML that represents the application context. The following code shows the context XML and bean definitions in creating a course use case:

Listing 1. XML and Bean definitions
<beans><bean id= "Course" class= "demo. Course "><property name=" module "ref=" module "/>  </bean><bean id=" module "class=" demo. Module "><property name=" assignment "ref=" assignment "/>  </bean><bean id=" assignment "class=" Demo. Assignment "/></beans>

The XML above is the code you will typically write when you use Spring to configure the bean. This XML code defines the Course bean, which references the Module bean. ModuleThe Bean has a Assignment reference to a bean. You now want to delete this XML and write Java code with the same effect. You will use a Java-based configuration to define the bean specified above. We will replace the XML with the Java class, which will now be used as the platform for Bean configuration. We'll name this class AppContext.java . The following code shows the AppContext class.

Listing 2. The AppContext configuration class that contains the bean definition
@Configurationpublic class AppContext {@Beanpublic Course Course () {Course Course = new Course (); Course.setmodule (module ()); return course;} @Beanpublic Module module () {module module = new Module (); Module.setassignment (Assignment ()); return module;} @Beanpublic Assignment Assignment () {return new Assignment ();}}

As you can see from the code above, it is now possible to programmatically define a bean as part of a Java-based configuration. AppContextclass now represents the configuration class as XML. This is achieved through @Configuration the use of annotations. @Configurationthe comment is at the top of the class. It tells the Spring container that the class is a configuration class that has bean definitions and dependencies. @Beanannotations are used to define beans. The above comment is located above the method that instantiates the bean and sets the dependency. The method name is the same as the Bean ID or default name. The return type of the method is the bean registered with the Spring application context. You can use the Bean setter method to set dependencies, which the container calls to connect the related items. Java-based configuration is also considered a comment-based configuration.

Registering a configuration class with Annotationconfigapplicationcontext

In traditional XML methods, you can use ClassPathXmlApplicationContext classes to load external XML context files. However, there is a class when using a Java-based configuration AnnotationConfigApplicationContext . AnnotationConfigApplicationContextclass is ApplicationContext an implementation of an interface that enables you to register the annotated configuration class. The configuration class here is declared with a @Configuration comment AppContext . After registering the class, @Bean all bean types returned by the commented method are also registered. The following code demonstrates the AnnotationConfigApplicationContext use of a class:

Listing 3. Registering the AppContext class with Annotationconfigapplicationcontext
public static void Main (string[] args) {  ApplicationContext ctx = new Annotationconfigapplicationcontext ( Appcontext.class);  Course Course = Ctx.getbean (course.class);  Course.getname ();}

As shown in the preceding code, AppContext the configuration class is registered by passing it to the AnnotationConfigApplicationContext constructor. In addition, you can use the method of the context class register to register the configuration class. The following code shows another approach.

Listing 4. Registering a AppContext class: Another way
public static void Main (string[] args) {  ApplicationContext ctx = new Annotationconfigapplicationcontext ();  Ctx.register (Appcontext.class)}

Registering the configuration class automatically registers the @Bean comment's method name, so its corresponding Bean is Course , Module and Assignment . You can then use the getBean method to get the related bean and invoke its business method. As you can see, writing a Java configuration class and registering it with the Spring context is straightforward. The next section discusses how to use Java-based configuration with a WEB application.

Configuring the Web Application

In the past, you typically used the XmlWebApplicationContext context to configure the Spring WEB application to specify the path to the external XML context file in Web Deployment descriptor file XML. XMLWebApplicationContextis the default context class used by the Web application. The following code describes the web.xml elements that point to ContextLoaderListener an external XML context file that will be loaded by the listener class.

Listing 5. XML with external XML context file
<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 will web.xml change the above code in to use the AnnotationConfigApplicationContext class. Remember that XmlWebApplicationContext Spring is the default context implementation used by the WEB application, so you never have to web.xml explicitly specify this context class in your file. You will now use Java-based configuration, so when you configure a WEB application, you need to specify the class in the web.xml file AnnotationConfigApplicationContext . The above code will be modified as follows:

Listing 6. Modified Web. XML using Annotationconfigapplicationcontext
<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 modification web.xml now defines the AnnotationConfigWebApplicationContext context class as a context parameter and as part of the servlet element. The context configuration location now points to the AppContext configuration class. This is very simple. The next section demonstrates the Bean's lifecycle callback and the implementation of the scope.

Implement bean lifecycle callbacks and range life-cycle callbacks

You can also use Java-based configuration to manage the bean lifecycle. @Beansupports two properties, the initMethod and destroyMethod , which can be used to define life cycle methods. The container invokes the life cycle method when the bean is instantiated or it is about to be destroyed. The life cycle method is also known as a callback method, because it is called by the container. @Beanbeans registered with annotations also support the standards and annotations specified by JSR-250 @PostConstruct @PreDestroy . If you are using an XML method to define a bean, you should use the bean element to define the lifecycle callback method. The following code shows a method that typically uses bean elements to define callbacks in an XML configuration.

Listing 7. Using XML methods to implement life cycle callbacks
<bean id= "Course" class= "demo. Course "init-method=" Setup "destroy-method=" cleanup "><property name=" module "ref=" module "/></bean>

The following code demonstrates the life cycle approach using Java configuration

Listing 8. Implementing Bean Lifecycle methods using the AppContext configuration class
@Configurationpublic class AppContext {@Bean (Initmethod = "Setup", Destroymethod = "cleanup") public Course Course () {Cour SE course = new course (); Course.setmodule (module ()); return course;} @Bean (Initmethod = "Setup", Destroymethod = "cleanup") public Module module () {module module = new Module (); Module.setassig Nment (Assignment ()); return module;} ...} public class Course {private Module module;private String name;public Course () {}public void Setup () {this.name = "M100 Py Thagoras theorems "}public void Setmodule (module module) {this.module = module;} public void Cleanup () {module = null;}}

The above code re-accesses the AppContext configuration class. @Beanthe comment now has two additional attributes, i.e., initMethod and destroyMethod . They define the setup and cleanup of life cycle methods. These methods are implemented in registered beans and are eventually called by the container before the bean is initialized and destroyed. Here Course , for example, the bean provides a life cycle approach to implementation. The method that is implemented is the setup and cleanup . Similarly, you can Module Assignment implement these methods in the and bean.

Bean Range

The Bean's method is @Scope defined using the annotation. The way to achieve this goal in XML is to specify the scope property in the bean element.

Listing 9. Defining bean ranges using XML methods
<bean id= "Course" class= "demo. Course "scope=" prototype "><property name=" module "ref=" module "/></bean>

The following code shows the bean scope definitions that are configured with Java:

Listing 10. Defining bean ranges using the AppContext configuration class
@Configurationpublic class AppContext {@Bean (Initmethod = "Setup", Destroymethod = "cleanup") @Scope ("prototype") public Course Course () {Course Course = new Course (); Course.setmodule (module ()); return Course;} ...}

As you can see in the code above, it is very easy to define the scope of the bean in a Java configuration class. The above AppContext configuration class uses @Scope annotations to Course define a prototype range for the bean. The default range is singleton.

There are many things you can do with Java configuration. This article only touches on some basic content. Using Java configuration has no significant advantage, it is just an alternative to the XML configuration provided by Spring. This is an excellent way to implement configuration for people who do not like to use XML in the framework. But the downside is also obvious, and if you make any changes to the configuration in the Java class, you must recompile the application.

Original: http://www.ibm.com/developerworks/cn/webservices/ws-springjava/

Spring Bean Management with Java configuration--Go to

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.