Spring Java配置

Java配置

Java配置是Spring 4.x推荐的配置方式,可以完全替代xml配置;
Java配置也是Sping Boot 推荐的配置方式。
Java配置是通过@Configuration和@Bean来实现的。
@Configuration 声明当前类是一个配置类,相当于一个Spring配置的xml文件。
@Bean 注解在方法上,声明当前方法的返回值为一个Bean。
使用原则:
全局配置使用Java配置(如数据库相关配置、MVC相关配置),业务Bean的配置使用注解配置
(@Service、@Component、@Repository、@Controlle).

实例

编写功能类的Bean

package com.wisely.highlight_spring4.ch1.javaconfig;
//1
public class FunctionService {

public String sayHello(String word){
return "Hello " + word +" !";
}
}

代码解释
此处没有使用@Service声明Bean。


使用功能类的Bean
package com.wisely.highlight_spring4.ch1.javaconfig;

import com.wisely.highlight_spring4.ch1.javaconfig.FunctionService;
//1
public class UseFunctionService {
//2
FunctionService functionService;

public void setFunctionService(FunctionService functionService) {
this.functionService = functionService;
}

public String SayHello(String word){
return functionService.sayHello(word);
}
}
代码解释
此处没有使用@Service声明Bean
此处没有使用@Autowired注解注入Bean


配置类
package com.wisely.highlight_spring4.ch1.javaconfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration //1
public class JavaConfig {
@Bean //2
public FunctionService functionService(){
return new FunctionService();
}

@Bean
public UseFunctionService useFunctionService(){
UseFunctionService useFunctionService = new UseFunctionService();
useFunctionService.setFunctionService(functionService()); //3
return useFunctionService;

}
}

代码解释
使用@Configuration注解表明当前类是一个配置类,这意味着这个类里可能有0个或者多个@Bean注解,此处没有使用包扫描,是因为所以的Bean都在此类中定义了。
使用@Bean注解声明当前方法FunctionService的返回值是一个Bean,Bean的名称是方法名。
注入FunctionService的Bean时候直接调用 functionService().
package com.wisely.highlight_spring4.ch1.javaconfig;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(JavaConfig.class);

UseFunctionService useFunctionService = context.getBean(UseFunctionService.class);

FunctionService functionService = context.getBean(FunctionService.class);

System.out.println(useFunctionService.SayHello("java config"));

System.out.println(functionService.sayHello("faunjoe"));

context.close();
}
}





原文地址:https://www.cnblogs.com/faunjoe88/p/5675195.html