Spring — 3. 注解开发

1、前提准备(Spring4.x以后)

(1)导入spring-aop的依赖 

       (2)加入Context约束,增加注解的支持,以及加入扫描的路径配置

<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
        http://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/>
    <context:component-scan base-package="com.tc"/>

</beans>

2、 注解详解

        2.1 Bean注入 ——  @Component(“user”)

定义Bean,向Spring的IOC容器注入Bean对象,等价于:

<bean id="user" class="com.tc.entity.User"/>

@Component 也可以不指定名,在获取bean对象时使用按类型获取的方式

BeanDao bean = context.getBean(BeanDao.class);
import org.springframework.stereotype.Component;

@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void print(){
        System.out.println("打印user");
    }
}

注:为了代码层次清晰,根据MVC设计模式,衍生出对应的3个注解,功能完全一致,名称不同而已

  •  @Repository:该注解用于数据访问层的bean定义,数据访问层也就是我们常写的dao层、mapper层。
@Repository("beanDao")
// @Repository
public class BeanDaoImpl implements BeanDao {
    public void save() {
        System.out.println("beanDao save...");
    }
}
  • @Service:该注解用于业务逻辑层的bean定义,即service层。
@Service("beanService")
// @Service
public class BeanServiceImpl implements BeanService {
    public void save() {
        System.out.println("bean service save...");
    }
}
  • @Controller:该注解用于表现层,控制层的bean定义,即controlle层
@Controller("beanController")
// @Controller
public class BeanController {
}

        2.2 属性值注入 —— @Value

向Bean的属性注入值,相当于

<bean id="user" class="com.tc.entity.User">

        <property name="name" value="jack"/>

</bean>

@Component
public class User {

    @Value("jack")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void print(){
        System.out.println(name);
    }
}

         2.3 自动装配 —— @Autowire,@Resource

        详见spring—— 2.IOC章节 

        2.4 作用域 —— @Scope

@Component
@Scope("singleton")
public class User {

    @Value("jack")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void print(){
        System.out.println(name);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值