Using Java annotations for Spring Bean management __java

Source: Internet
Author: User

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

Overview

As we all know, the Spring framework is a driving factor in the control reversal (IOC) or Dependency injection (DI) pattern, which is implemented through a container based configuration. In the past, Spring allows developers to use xml-based configurations to manage bean dependencies by leveraging application context XML files. This file is outside the application and contains the definition of the bean and its dependencies with that application. Although using XML configuration is simpler and easier, there is still another way to define beans and their dependencies. This approach is also known as a java-based configuration. Unlike XML, a java-based configuration enables you to manage beans programmatically. This can be achieved by using a variety of annotations. This article will demonstrate the Java configuration example and compare it to traditional XML configuration methods. This article will demonstrate the basics of java-based configuration by following these steps: Understanding @Configuration and @Bean Annotations Configuring a WEB application implementation Bean by using the Annotationconfigapplicationcontext registration configuration class Life cycle callbacks and scopes

We will use the "Create course" use case of an online university. When you create a course, you create a theme or module, 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 Module bean, which contains a reference to the assignment bean. Understanding @Configuration and @Bean annotations

In the ideal scenario, you can define the bean in the XML that represents the application context. The following code shows the context XML and the bean definition in the Create course 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 above XML is the code that you typically write when you use the Spring configuration bean. This XML code defines the Course bean, which references the Module bean. The Module Bean has a reference to a assignment bean. You are now going to delete this XML and write the equivalent Java code. 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 a platform for the bean configuration. We'll name this class Appcontext.java. The following code shows the Appcontext class. Listing 2. Appcontext configuration class containing the bean definition

 @Configuration public class Appcontext {@Bean public Course Course () {Course Course = new Course ();
		Course.setmodule (module ());
	return course;
		@Bean Public Module module () {Module module = new module ();
		Module.setassignment (Assignment ());
	return module;
	@Bean Public Assignment Assignment () {return new assignment (); }
}

As you can see from the above code, the bean is now programmatically defined as part of a java-based configuration. The Appcontext class now represents the configuration class as XML. This is accomplished by using @Configuration annotations. @Configuration note is at the top of the class. It tells the Spring container that this class is a configuration class that has bean definitions and dependencies. @Bean annotations are used to define beans. The above comment is above the method that instantiates the bean and sets the dependencies. The method name is the same as the bean ID or the default name. The return type of the method is the bean that is registered to the Spring application context. You can use the bean's setter method to set dependencies, which the container calls to connect the dependencies. Java-based configurations are also considered to be based on annotation configurations. registering the configuration class with Annotationconfigapplicationcontext

In traditional XML methods, you can use the Classpathxmlapplicationcontext class to load an external XML context file. However, when using a java-based configuration, there is a Annotationconfigapplicationcontext class. The Annotationconfigapplicationcontext class is an implementation of the ApplicationContext interface, enabling you to register the annotated configuration class. The configuration class here is the appcontext that uses the @Configuration annotation declaration. After registering the class, all Bean types returned by the method @Bean annotation are also registered. The following code demonstrates the use of the Annotationconfigapplicationcontext class: listing 3. Use Annotationconfigapplicationcontext to register Appcontext classes

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

As the above code shows, the Appcontext configuration class is registered by passing it to the Annotationconfigapplicationcontext constructor. In addition, you can register the configuration class by using the Register method of the context class. The following code shows another method. Listing 4. Registering the Appcontext class: Another method

public static void Main (string[] args) {
  ApplicationContext ctx = new Annotationconfigapplicationcontext ();
  Ctx.register (Appcontext.class)
}

Registering the configuration class automatically registers the method name of the @Bean annotation, so its corresponding Bean is Course, Module, and assignment. You can then use the Getbean method to get the relevant bean and call its business method. As you can see, writing a Java configuration class and registering it with the Spring context is simple. The next section discusses how to use a java-based configuration with a WEB application. Configuring WEB Applications

In the past, you would typically use the Xmlwebapplicationcontext context to configure the Spring Web application, which is to specify the path to 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 an external XML context file that will be loaded by the Contextloaderlistener listener class. Listing 5. Web.xml using an 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 want to change the above code in  web.xml  to use the  AnnotationConfigApplicationContext  class. Remember that,xmlwebapplicationcontext  is the default context implementation that Spring uses for WEB applications, so you never have to explicitly specify this context class in your  web.xml  file. Now you will use a java-based configuration, so you need to specify the  AnnotationConfigApplicationContext  class in the  web.xml  file when you configure your WEB application. The preceding 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.sp Ringframework.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.springframewor K.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.SPR Ingframework.web.context. Support. Annotationconfigwebapplicationcontext </param-value> </init-param> </servlet> ... </web-app >

The 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 will demonstrate the implementation of the bean's lifecycle callback and scope. Implementing a bean Lifecycle callback and scope Life Cycle Callback

You can also use a java-based configuration to manage the life cycle of your beans. @Bean supports two properties, Initmethod and Destroymethod, that can be used to define life cycle methods. When the bean is instantiated or is about to be destroyed, the container can call the lifecycle method. The lifecycle method is also known as a callback method because it is invoked by the container. Beans registered using @Bean annotations also support the standard @PostConstruct and @PreDestroy annotations specified by JSR-250. 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 a bean element to define callbacks in an XML configuration. Listing 7. Implementing a lifecycle callback using an XML method

<bean id= "Course" class= "demo. Course "init-method=" Setup destroy-method= "cleanup" >
	<property name= "module" ref= "module"/>
< /bean>

The following code demonstrates the lifecycle method using Java configuration Listing 8. Implementing the Bean Lifecycle method with the Appcontext configuration class

 @Configuration public class Appcontext {@Bean (Initmethod = "Setup", Destroymethod = "cleanup") public Course Course ()
		{Course Course = new Course ();
		Course.setmodule (module ());
	return course;
		@Bean (Initmethod = "Setup", Destroymethod = "cleanup") public Module module () {Module module = new module ();
		Module.setassignment (Assignment ());
	return module;		
}
	
	...
}
	public class Course {private Module module;
	
	private String name; Public Course () {} public void Setup () {this.name = ' M100 Pythagoras theorems '} public void Setmodule (Module
	module) {this.module = module;
	public void Cleanup () {module = null; }
}

The code above accesses the Appcontext configuration class again. @Bean Note now has two additional attributes, namely Initmethod and Destroymethod. They define the setting and elimination of life cycle methods. These methods are implemented in a bean that has already been registered, and are eventually invoked by the container before the bean is initialized and destroyed. Here, for example, the Course bean provides a lifecycle method implementation. The method implemented is setup and cleanup. Similarly, you can implement these methods in Module and assignment beans. Bean Range

The method of the bean is defined using @Scope annotation. The way to achieve this in XML is to specify the scope attribute in the bean element. Listing 9. Define the bean scope using the XML method

<bean id= "Course" class= "demo. Course "scope=" prototype ">
	<property name=" module "ref=" module "/>
</bean>
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.