一:Spring 4x 中的三种注解类:
声明bean的注解:
1、@Component组件
2、@Service在逻辑层使用
3、@Respository在数据层dao使用
4、@Controller在表现层使用
注入Bean的注解:
@Autowired:
@Inject
@Resource:
配置注解
@Configuration声明当前类位配置类(xml)。
@ComponentSan自动扫描包,扫描改层下所有声明bean的注解类,并且向spring容器中注册为bean;
二:举例
1.声明功能类Bean
Packagetgb;
@Service//@component、@Service 、@Repository
Publicclass FunctionService{
public String sayHello(){return"hello"}
}
2.注入类
Packagetgb;
@Service//@component、@Service 、@Repository
Publicclass UseFunctionService{
@Autowired
Functionservice functionservice;
public String sayHello(){
return functionservice.sayHello();
}
}
3.配置类
Packagetgb;
@Configuration
@ComponentScan("tgb")
Publicclass Diconfig{
}
4.运行
Publicclass Main{
public static void mian(String[] args){
AnnotationConfigApplicationContextcontext=new AnnotationConfigApplicationContext(DiConfig.class);
UseFunctionServcie useFunctionServcie =context.getBean(UseFunctionService.class);
usrFunctionService.sayHello();
context.close();
}
}