Spring: hard-coded bean injection instance

Source: Internet
Author: User

<Beans>
<Bean id = "messageSource" class = "org. springframework. context. support. ResourceBundleMessageSource">
<Property name = "basename" value = "messages"/>
<Property name = "useCodeAsDefaultMessage" value = "true"/>
</Bean>
</Beans>

Manual encoding injection is now performed to reduce the configuration file:

 

Public class TestRegisterBean {

Public static void main (String [] args ){

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext (
"ApplicationContext. xml"); // you can obtain it in the web environment by using the following method:
// WebApplicationContextUtils. getRequiredWebApplicationContext (servletContextEvent
. GetServletContext ());
 
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)

ApplicationContext. getBeanFactory ();
GenericBeanDefinition messageSourceDefinition = new GenericBeanDefinition ();
 
// For parameters, see www.2cto.com in the preceding configuration file.
Map <String, String> original = new HashMap <String, String> ();
Original. put ("basenames", "messages ");
Original. put ("usecodeasdefamessage message", "true ");
MessageSourceDefinition. setBeanClass (ResourceBundleMessageSource. class );
MessageSourceDefinition. setPropertyValues (new MutablePropertyValues (original ));
// Register
BeanFactory. registerBeanDefinition ("ResourceBundleMessageSource ",
MessageSourceDefinition );
// Obtain
ResourceBundleMessageSource messageSource = (ResourceBundleMessageSource) applicationContext
. GetBean ("ResourceBundleMessageSource ");
// Test
System. out. println (messageSource. getMessage ("test", null, null ));
}

}


To test this instance, create messages_zh_CN.properties under classpath and add test.

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.