Spring 4x中的注解类使用


一: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();
 
 
}
 
}


评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值