spring使用注解开发

本文介绍了在Spring 4.0以后如何通过注解进行开发,包括引入aop依赖、配置context、扫描带注解的类,并重点讲解了@Component、@Value和@Autowired等注解的使用及其衍生注解在DAO、Service和Controller中的应用。
摘要由CSDN通过智能技术生成

1.在spring4之后,要使用注解开发,必须要导入aop包,只需导入spring-webmvc依赖里边包含了这个包

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>

在这里插入图片描述

2.在配置文件中,需要确定context的约束是否正确,再进行配置

  • 导入约束:
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/springcontext.xsd"
  • 进行配置
<!--指定要扫描的包这个包中类的注解会生效-->
    <context:component-scan base-package="com.fsp.pojo"/>
    <!--配置注解的支持-->
    <context:annotation-config/>

即:

<?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
       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:component-scan base-package="com.fsp.pojo"/>
    <!--配置注解的支持-->
    <context:annotation-config/>

</beans>

3.在相应的类及属性上进行注解

//注入类,放在类前
@Component
public class User {
    //注入属性值,放在属性前
    @Value("fsp")
    public String name;
}

@Component放在类上:指定要扫描包中的类会生效
@Value("")放在属性上,进行赋值
@Autiwired放在引用类型,即对象前

4.注解的衍生:

@Component(扫描包中的类)有几个衍生的注解,在dao、service、controller上作用都一样:

  • dao:[@Repository]
  • service:[@Service]
  • controller:[@Conrtoller]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值