spring常用注解

Spring的一个核心功能是IOC,就是将Bean初始化加载到容器中,Bean可以使用Spring注解方式或者Spring XML配置方式加载到容器中。

一,组件类注解

@Component :标准一个普通的spring Bean类。
@Repository:标注一个DAO组件类。
@Service:标注一个业务逻辑组件类。
@Controller:标注一个控制器组件类。

注意:@Component可以代替@Repository,@Service,@Controller。因为这三个注解是被@Component标注的。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface test {
    String value() default "";
}

1,当一个组件访问Dao层时可以使用@Repository进行注解

@Repository
public class DaoImpl implements Dao{
public void test(){
}

2,当一个组件代表业务层时,我们使用@Service进行注解

@Service(value="TestService")
//使用@Service注解不加value ,默认名称是Service
public class ServiceImpl implements Service {
    @Autowired
    private Dao dao;
 }

3,当一个组件作为前端交互的控制层,使用@Controller进行注解

@Controller
public class Controller {
    @Autowired 
    private Service service;
}

指定了某些类可作为Spring Bean类使用后,最好还需要让spring搜索指定路径,在Spring配置文件加入如下配置:

<context:component-scan base-package="org.springframework.*"/>

二:装配bean时常用的注解

1、注解介绍

@Autowired:属于Spring org.springframework.beans.factory.annotation包下,可用于为类的属性、构造器、方法进行注值

@Resource:不属于spring的注解

@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行

1,@Autowired

@Controller
public class Controller {
    @Autowired //默认依赖的Dao 对象(Bean)必须存在
    //@Autowired(required = false) 改变默认方式
    @Qualifier("Service")
    private Service service;
}

2,@Resource

public class AnotationTest {
    @Resource(name = "myTest")
    private Test test;
}

以上就是一些基本的spring注解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值