Java配置的基本使用
- 新建一个功能类
package com.xiaohan.javaconfig;
public class FunctionService {
public String sayHello(String word){
return "Hello " + word;
}
}
- 新建一个使用功能类的类
package com.xiaohan.javaconfig;
public class UseFunctionService {
FunctionService functionService;
public void setFunctionService(FunctionService functionService) {
this.functionService = functionService;
}
public String sayHello(String word) {
return functionService.sayHello(word);
}
}
- 新建一个Java配置类
package com.xiaohan.javaconfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// 声明这是一个Java配置类
@Configuration
public class JavaConfig {
// 实例化 功能类
@Bean
public FunctionService functionService() {
return new FunctionService();
}
// 实例化 使用功能类的类
@Bean
public UseFunctionService useFunctionService(FunctionService functionService) {
UseFunctionService useFunctionService = new UseFunctionService();
// 注入功能类
useFunctionService.setFunctionService(functionService);
return useFunctionService;
}
}
- 创建一个Main方法 初始化容器 并测试
package com.xiaohan.javaconfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// Java配置
public class Main {
public static void main(String[] args) {
// 指定配置类 初始化 Spring容器 可指定多个配置类
ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class);
UseFunctionService useFunctionService = ac.getBean(UseFunctionService.class);
System.err.println(useFunctionService.sayHello("JavaConfig"));
//Hello JavaConfig
}
}
网友评论