Java配置
Java配置
Java配置是Spring 4.x和SpringBoot推荐的方式。 Java配置是通过@Configuration和@Bean来实现的:
- @Configuration声明当前类是一个配置类,相当于一个Spring配置的xml文件。
- @Bean注解在方法上,声明当前方法的返回值是一个Bean。
java config的demo
项目结构
Main
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(JavaConfig.class); //1
UseFunctionService useFunctionService = applicationContext.getBean(UseFunctionService.class); //2
System.out.println(useFunctionService.SayHello("JavaConfig"));
applicationContext.close();
}
}
JavaConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JavaConfig {
@Bean
public FunctionService functionService(){
return new FunctionService();
}
@Bean
public UseFunctionService userFunctionService(){
UseFunctionService useFunctionService = new UseFunctionService();
useFunctionService.setFunctionService(functionService());//3
return useFunctionService;
}
}
FunctionService
public class FunctionService {
public String sayHello(String word){
return "Hello " + word + "!";
}
}
UseFunctionService
public class UseFunctionService {
FunctionService functionService;
public FunctionService getFunctionService() {
return functionService;
}
public void setFunctionService(FunctionService functionService) {
this.functionService = functionService;
}
public String SayHello(String word) {
return functionService.sayHello(word);
}
}