javaEE颠覆者第一章
1.3.2 java配置
(1)编写功能类的bean
package spring4.javaconfig;
//@service 注解除去了
public class FunctionService {
public String sayHello(String word) {
return "hello "+word+"!";
}
}
(2)使用功能类的bean
package spring4.javaconfig;
//@service 注解除去了
public class UserFunctionService {
//@@Autowired注解除去了
FunctionService functionService;
public String sayHello(String word) {
return functionService.sayHello(word);
}
public void setFunctionService(FunctionService functionService) {
this.functionService =functionService;
}
}
(3)配置类
package spring4.javaconfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration//表明当前类是一个配置类 意味着这里可能有多个bean注解
public class JavaConfig {
@Bean//声明当前方法FunctionService 返回值是一个bean bean名称是方法名
public FunctionService functionService() {
return new FunctionService();
}
@Bean
public UserFunctionService userFunctionService() {
UserFunctionService userFunctionService =new UserFunctionService();
userFunctionService.setFunctionService(functionService());//直接调用functionService方法
return userFunctionService;
}
// @Bean
// public UserFunctionService userFunctionService(FunctionService functionService) {
//将functionService作为参数传输 。在spring容器中,只要容器中存在某个bean, 就可以在另外一个Bean的生命方法的参数注入
// UserFunctionService userFunctionService=new UserFunctionService();
// userFunctionService.setFunctionService(functionService);
// return userFunctionService;
// }
}
(4)运行
package spring4.javaconfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context
= new AnnotationConfigApplicationContext(JavaConfig.class);//使用AnnotationConfigApplicationContext 作为Spring容器 接受一个配置类作为参数
UserFunctionService userFunctionService
=context.getBean(UserFunctionService.class);
System.out.println(userFunctionService.sayHello("java config"));//获取声明的bean
context.close();
}
}
结果