Spring 3.0 adds @configuration, @Value, @Bean following a simple example
@Configuration: You can replace the bean configuration of an XML file with a Java file
@Value: Read xxx.properties into Java file for key-value pair injection
@Bean: @Configuration instantiate the Bean. Name: Specify the bean name
@Configuration code is as follows
Package guoguo.spring.config;
Import Guoguo.spring.config.impl.WorkerImpl;
Import Org.springframework.beans.factory.annotation.Value;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
@Configuration public
class AppConfig {
private @Value ("#{jdbcproperties.url}") String Jdbcurl;
Private @Value ("#{jdbcproperties.username}") String username;
Private @Value ("#{jdbcproperties.password}") String password;
@Bean (name = "worker") public
worker Getworker () {
return new Workerimpl ();
}
Test key value injected public
String Getjdbcurl () {
return jdbcurl;
}
Public String GetUserName () {
return username;
}
Public String GetPassword () {
return password;
}
}
The XML file is configured as follows
<?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:util= "http://www.springframework.org/ Schema/util "
xmlns:context=" Http://www.springframework.org/schema/context "
xsi:schemalocation="/http/ Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http ://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http ://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd " >
<util:properties id= "jdbcproperties" location= "Resources/env/jdbc.properties" ></util: properties>
<context:component-scan base-package= "guoguo.spring"/>
</beans>
Test file
Package guoguo.spring.config;
Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
public class Testappconfig {
@Test public
void SetUp () throws Exception {
ApplicationContext context = new Cla Sspathxmlapplicationcontext (GetContext ());
Set the configuration file portion of the service corresponding business
//annotationconfigapplicationcontext context = new Annotationconfigapplicationcontext ( Appconfig.class);
AppConfig AppConfig = Context.getbean (appconfig.class);
System.out.println ("Jdbcurl [" + appconfig.getjdbcurl () + "]");
SYSTEM.OUT.PRINTLN ("username [" + appconfig.getusername () + "]");
Worker worker = Context.getbean ("worker", Worker.class);
System.out.println (Worker.dowork ());
}
Public string[] GetContext () {
return new string[] {"Classpath*:resources/context.xml"};
}
}
Test results
Jdbcurl [1234123]
username [1231231] This is
worker Impl