Spring-使用注解开发

1.@Component(注册bean)

在Spring4之后,要使用注解开发,必须要保证导入aop的包

使用注解就要导入context约束,增加注解的支持 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		   https://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd">


    <context:annotation-config/>


</beans>

这里再添一个约束,用来让spring扫描指定路径下的包,这样就可以让spring自动创建bean 

    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.sun.pojo"/>

 上面约束对应的注解,@Component,把这个类注册到Spring中(也就是让Spring为其生成一个bean来托管)

@Component
public class User {
    public String name = "小明";
}

2.衍生的注解

@Component有几个衍生的注解,我们在web开发中,会按照mvc三层架构分层

  • dao               【@Repository】
  • service         【@Service】
  • controller      【@Controller】

上面三个注解和@Component一样,都代表将这个类注册到Spring中,装配bean 

3.@Autowired(自动装配)

该注解在我下面这个博客有详细介绍

Spring-自动装配bean-CSDN博客

4.@Value(属性注入)

该注解相当于是:

<property name="name" value="小明"/>

public class User {
    @Value("小明")
    public String name;
}

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值