我欲穿花寻路,直入白云深处,浩气展虹霓。
Spring
@Configuration
注解有助于基于Spring
注解的自动装配。@Configuration
注解指示一个类声明了一个或多个@Bean
方法,Spring
容器可以对该类进行处理,以便在运行时为这些bean
生成bean
定义和服务请求。。
从spring 2
开始,我们就将bean
配置写入xml
文件中。但是Spring 3
允许将bean
定义移出xml
文件。我们可以在Java
文件本身中给出bean
定义。这称为Spring
Java Config
功能(使用@Configuration
注解)
Spring
@Configuration
注解用法在任何类顶部使用@Configuration
注解来声明该类提供了一个或多个@Bean
方法,并且可以由Spring
容器进行处理以在运行时为这些bean
生成bean
定义和服务请求。
@Configuration
public class AppConfig {
@Bean(name="demoService")
public DemoClass service()
{
}
}
Spring
@Configuration
注解示例@Configuration
注解的用法。
maven
项目mvn archetype:generate
-DgroupId=cn.howtodoinjava.core
-DartifactId=springCoreTest
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
mvn eclipse:eclipse
Spring
依赖项<properties>
<spring.version>3.0.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- For JavaConfig -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>
spring
bean
public interface DemoManager {
public String getServiceName();
}
public class DemoManagerImpl implements DemoManager
{
@Override
public String getServiceName()
{
return "My first service with Spring 3";
}
}
Spring
配置类import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import cn.howtodoinjava.core.beans.DemoManager;
import cn.howtodoinjava.core.beans.DemoManagerImpl;
@Configuration
public class ApplicationConfiguration {
@Bean(name="demoService")
public DemoManager helloWorld()
{
return new DemoManagerImpl();
}
}
测试Java Config
可配置的bean
。
package cn.howtodoinjava.core.verify;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.howtodoinjava.core.beans.DemoManager;
import com.howtodoinjava.core.config.ApplicationConfiguration;
public class VerifySpringCoreFeature
{
public static void main(String[] args)
{
ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
DemoManager obj = (DemoManager) context.getBean("demoService");
System.out.println( obj.getServiceName() );
}
}