Spring使用注解开发

Spring使用注解开发


在Spring4之后,要使用注解开发,必须要保证aop包的导入(maven依赖中会自动导入相关的包)
在这里插入图片描述
引用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:component-scan base-package="com.lding"></context:component-scan>
    <context:annotation-config/>
</beans>

Bean的注入

我们之前都是使用 bean 的标签进行bean注入,但是实际开发中,我们一般都会使用注解!

  1. 配置扫描哪些包下的注解(扫描组件)
     <!-- 扫描组件-->
    <context:component-scan base-package="com.lding"></context:component-scan>
    
  2. 在指定包下编写类,增加注解
    @Component
    public class User {
        public String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    
  3. 测试
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = context.getBean("user", User.class);
        System.out.println(user.name);
    }
}

属性注入

使用注解注入属性

  1. 可以不用提供set方法,直接在直接名上添加@value(“值”)
    @Component
    public class User {
        //相当于<property name="name" value="冷丁"></property>
        @Value("冷丁")
        public String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    
  2. 如果提供了set方法,在set方法上添加@value(“值”);
@Component
public class User {
    //相当于<property name="name" value="冷丁"></property>

    public String name;
    public String getName() {
        return name;
    }
    @Value("冷丁")
    public void setName(String name) {
        this.name = name;
    }
}

衍生注解

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

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

包括Component在内,这四个功能都是一样的,都是代表讲某个类注册到Spring容器中,装配Bean

自动装配注解

参考上一篇文章,@Autowire和@Resource

作用域

@scope

  • singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
  • prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收
@Controller("user")
@Scope("prototype")
public class User {
@Value("冷丁")
public String name;
}

如果对您有帮助,免费的赞点一个~~~感谢🙏

在这里插入图片描述

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值