一、概念解析#
java配置是通过@Configuration、@Bean实现。
@Configuration声明当前类是一个配置类,相当于一个Spring的XML配置文件。
@Bean注解到方法上声明当前方法返回值是一个Bean。
二、Demo#
1、一个功能类的Bean
package com.springconfig.test;
public class FunctionService(){
public String printHappy(String UserName){
return UserName+"Happy";
}
}
2、使用功能类的Bean
package com.springconfig.test;
public class UseFunctionService(){
FunctionService functionService;
public void setFunctionService(FunctionService functionService){
this.functionService = functionService;
}
public String printHappy(String UserName){
return functionService.printHappy(UserName);
}
}
3、配置类
//第一种方式
package com.springconfig.test;
@Configuration
public class JavaConfig(){
//声明这个方法返回一个Bean,Bean的名字就是方法名。此处应该返回functionService这个Bean
@Bean
public FunctionService functionService(){
return new FunctionService ();
}
@Bean
public UseFunctionService useFunctionService(){
UseFunctionService useFunctionService = new useFunctionService();
//给useFunctionService 这个Bean注入functionService()方法返回的Bean
useFunctionService .setFunctionService(functionService())
return useFunctionService;
}
}
//第二种方式
package com.springconfig.test;
@Configuration
public class JavaConfig(){
@Bean
//直接将FunctionService 这个Bean作为参数传入useFunctionService()方法
public UseFunctionService useFunctionService(FunctionService functionService){
UseFunctionService useFunctionService = new useFunctionService();
//注入functionService这个Bean
useFunctionService .setFunctionService(functionService)
return useFunctionService;
}
}
4、Main启动类
package com.springconfig.test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main(){
public static void main(String[] args){
//使用Spring AnnotationConfigApplicationContext容器读取Config这个配置类
AnnotationConfigApplicationContext comtext = new AnnotationConfigApplicationContext(JavaConfig.class);
//获取context容器中的实例化Bean UseFunctionService
UseFunctionService useFunctionService = context.getBean(UseFunctionService.class);
system.out.println(useFunctionService.printHappy("冉玉琦"));
context.close();
}
}