Spring (3) Bean continue to get started, Spring Bean continue to get started

Source: Internet
Author: User

Spring (3) Bean continue to get started, Spring Bean continue to get started
I. Aware related interfaces

For applications, the degree of coupling to the Sping Api should be minimized. However, in some cases, to use some functions provided by Spring, it is necessary to let the Bean understand the details of Spring container management, such as letting the Bean know that the Bean is managed by that name in the container, or letting the Bean know the existence of BeanFactory or ApplicationContext, that is, the Bean can obtain BeanFactory or ApplicationContext instances. If the Bean can realize these objects, it can perform operations such as event publishing when some Bean actions occur.

1.1. Spring provides some Aware interfaces:

BeanNameAware interface:If a bean needs to access the id attribute of its own bean in the configuration file, this Bean class provides the callback capability after the dependency is determined and before the initialization method, to obtain the bean id attribute, this interface provides the void setBeanName (String name) method implementation. It must be noted that the name parameter of this method is the bean id attribute, the setBeanName method allows the bean to obtain its own id attribute.

BeanFactoryAware interface:Bean that implements the BeanFactoryAware interface can directly access the spring container through beanfactory. After the bean is created by the container, a corresponding beanfactory instance will be referenced, this interface has a void setBeanFactory (BeanFactory beanFactory) method to create its BeanFactory instance through the parameters of this method, implementing the BeanFactoryAware interface, so that the Bean can have the ability to access the Spring container.Disadvantage: code is coupled with spring APIs. This method is not recommended.

ApplicationContextAware interface:After the Bean class is initialized, it will be injected into the applicationContext instance. This interface has a method, setApplicationContext (ApplicationContext context), which uses its parameter context to create its applicationContext instance,Disadvantage: code is coupled with spring APIs. This method is not recommended.

1.2,BeanNameAware interface:
Package com. pb. entity; import org. springframework. beans. factory. beanNameAware;/** the entity class implements the init method and the BeanNameAware interface */public class Hello implements BeanNameAware {@ Override public void setBeanName (String arg0) {System. out. println ("Callback setBeanName method id attribute is" + arg0);} public void init () {System. out. println ("executing initialization method init ");}}

ApplicationContext. xml

<bean id="hello" class="com.pb.entity.Hello" init-method="init"></bean>

Test class:

package com.pb.demo;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.pb.entity.Hello;public class HelloTest {    public static void main(String[] args) {        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");        Hello hello=context.getBean("hello",Hello.class);    }}

Result:

The callback setBeanName method id attribute is hello. The initialization method init is being executed.
1.3,BeanFactoryAware interface:
Package com. pb. entity; import org. springframework. beans. beansException; import org. springframework. beans. factory. beanFactory; import org. springframework. beans. factory. beanFactoryAware; import org. springframework. beans. factory. beanNameAware;/** the entity class implements the init method and BeanNameAware interface */public class Hello implements BeanNameAware, BeanFactoryAware {private BeanFactory bf; @ Override public void setBeanName (String arg0) {System. out. println ("Callback setBeanName method id attribute is" + arg0);} public void init () {System. out. println ("executing initialization method init");}/** rewrite setBeanFactory Method * @ see org. springframework. beans. factory. beanFactoryAware # setBeanFactory (org. springframework. beans. factory. beanFactory) */@ Override public void setBeanFactory (BeanFactory arg0) throws BeansException {this. bf = arg0;} public BeanFactory getBf () {return bf ;}}

Configuration File unchanged

Test class:

Package com. pb. demo; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext; import com. pb. entity. hello; public class HelloTest {public static void main (String [] args) {ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext. xml "); Hello hello = context. getBean ("hello", Hello. class); System. out. println ("Get beanFactory object" + hello. getBf ());}}

Result:

The callback setBeanName method id attribute is hello. The initialization method init is being executed to obtain the beanFactory object org. springframework. beans. factory. support. defalistlistablebeanfactory @ 3dc0bb: defining beans [hello]; root of factory hierarchy

 

1.4,ApplicationContextAware interface:
Package com. pb. entity; import org. springframework. beans. beansException; import org. springframework. beans. factory. beanFactory; import org. springframework. beans. factory. beanFactoryAware; import org. springframework. beans. factory. beanNameAware; import org. springframework. context. applicationContext; import org. springframework. context. applicationContextAware;/** the entity class implements the init method and BeanNameAware interface */public class Hello implements BeanNameAware, BeanFactoryAware, ApplicationContextAware {private BeanFactory bf; private ApplicationContext context; @ Override public void setBeanName (String arg0) {System. out. println ("Callback setBeanName method id attribute is" + arg0);} public void init () {System. out. println ("executing initialization method init");}/** rewrite setBeanFactory Method * @ see org. springframework. beans. factory. beanFactoryAware # setBeanFactory (org. springframework. beans. factory. beanFactory) */@ Override public void setBeanFactory (BeanFactory arg0) throws BeansException {this. bf = arg0;} public BeanFactory getBf () {return bf;} @ Override public void setApplicationContext (ApplicationContext arg0) throws BeansException {this. context = arg0;} public ApplicationContext getContext () {return context ;}}

Configuration File unchanged

Test class

Package com. pb. demo; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext; import com. pb. entity. hello; public class HelloTest {public static void main (String [] args) {ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext. xml "); Hello hello = context. getBean ("hello", Hello. class); System. out. println ("Get beanFactory object" + hello. getBf (); System. out. println ("the obtained applicationContext object:" + hello. getContext ());}}

Result:

The property of the callback setBeanName method id is that hello is executing the initialization method init to get the beanFactory object org. springframework. beans. factory. support. defaultListableBeanFactory @ 3dc0bb: defining beans [hello]; root of factory hierarchy: applicationContext object: org. springframework. context. support. classPathXmlApplicationContext @ 1d04653: startup date [Wed Apr 08 00:43:06 CST 2015]; root of context hierarchy
2. BeanPostProcessor class and BeanFactoryPostProcessor

Process the Bean in the container

Implement BeanPostProcessor interface Bean post-Processor

Public Object postProcessAfterInitialization (Object arg0, String arg1); operations after bean Initialization

Public Object postProcessBeforeInitialization (Object arg0, String arg1); operations before bean Initialization

The first parameter initializes the Bean. The second parameter is the name of the Bean instance.

After the container is instantiated, the processor performs additional processing on the container.

BeanFactoryPostProcessor interface must be implemented,

Public void postProcessBeanFactory (ConfigurableListableBeanFactory arg0)

Spring plug provides many post-window processors such:

PropertyPlaceholderConfigurer: Property placeholder Configurator

PropertyOverrideConfigurer: another property placeholder Configurator

The difference between the two types is that they are covered with the latter type.

2.1,Propertyplaceholderpolicer

Is spring's built-in PropertyEdito, which is the implementation class of beanFactoryPostProcess

Purpose: Read the properties configuration file.

Through this implementation class, you can configure some attribute values in the spring configuration file to the properties file, so that the spring configuration file can be changed as long as the properties file is prefixed.

When you use PropertyPlaceholderConfigure to modify attributes of a certain part, you do not need to open the Spring configuration file to ensure that new errors are not introduced to the spring configuration file.

Advantage: Some configuration information can be separated from the main xml configuration file,

Multiple configuration files are supported. You can split the configuration file into multiple configuration files to reduce the risk of modifying the configuration file,

 

2.2,PropertyOverrideConfigurer

The configuration information in the XML file will be overwritten. The configuration in the. properties attribute file is the main one.

If not configuredPropertyOverrideConfigurer uses the configuration information in XML.

Attribute format:

BeanName. property = value

BeanName is the bean id attribute in the spring xml configuration to facilitate the proximity, and value is the attribute value. for multiple properties files, the locations attribute is used to specify

3. Custom Attribute Editor

Application scenarios:

Unrecognized type, such as date

Implementation

Inherit PropertyEditorSupport

Override setAsText () method

package com.pb.entity;import java.util.Date;public class AppDate {    private Date date;    public Date getDate() {        return date;    }    public void setDate(Date date) {        this.date = date;    }        }

Custom Editor

Package com. pb. entity; import java. beans. propertyEditorSupport; import java. text. parseException; import java. text. simpleDateFormat; public class CustomerProperty extends PropertyEditorSupport {private String format; @ Override public void setAsText (String text) throws IllegalArgumentException {SimpleDateFormat sdf = new SimpleDateFormat (format); // super. setAsText (text); try {// conversion object, which can be re-assigned through the setValue method this. setValue (sdf. parse (text);} catch (ParseException e) {e. printStackTrace () ;}} public String getFormat () {return format;} public void setFormat (String format) {this. format = format ;}}

ApplicationContext. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: p = "http://www.springframework.org/schema/p" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <! -- Define the bean class as the custom editor --> <bean class = "org. springframework. beans. factory. config. CustomEditorConfigurer"> <! -- Property --> <property name = "medmeditors"> <! -- Map --> <map> <! -- Key is the Date --> <entry key = "java. util. Date"> <! -- Configure map value --> <bean class = "com. pb. entity. CustomerProperty"> <! -- Configure Attributes --> <property name = "format" value = "yyyy-MM-dd"> </property> </bean> </entry> </map> </ property> </bean> <! -- Configure the bean of AppDate --> <bean id = "appDate" class = "com. pb. entity. appDate "> <property name =" date "> <value> 2014-4-8 </value> </property> </bean> </beans>

Test class:

package com.pb.demo;import java.text.SimpleDateFormat;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.pb.entity.AppDate;public class Demo {    /**     * @param args     */    public static void main(String[] args) {        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");        AppDate appDate=context.getBean("appDate",AppDate.class);        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");        System.out.println(sdf.format(appDate.getDate()));    }}

If you do not define a custom Editor, there is no way to inject the date type directly.

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.