【Spring】Spring中ioc的常用注解

本文深入解析Spring框架中注解的使用,包括@Component、@Controller、@Service等注解的作用及属性,@Autowired和@Qualifier如何实现依赖注入,@Resource的使用及依赖,@Value用于基本类型和String数据的注入,以及@Scope改变bean的作用范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

xml文件中的配置

<?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">
<!--告知spring在创建容器的时候要扫描的包
    配置的标签不在beans中,而是在context空间和约束中
    所以表头插入了xmlns:context-->

    <context:component-scan base-package="com.mj"></context:component-scan>
</beans>

用注解的方式实现xml的配置

1.用于创建对象==bean

@Component:
* 作用:用于把当前类对象存入spring容器中
* 属性:value:用于指定bean的id,不设置时默认的value值为类名的开头字母小写
@Controller 一般用于表现层
@Service 一般用于业务层
@Repository(仓库) 一般用于持久层

  • 以上三个注解的作用与属性与Component完全一致
    它们是spring框架为用户提供的三层使用注解,使我们的三层对象更加清晰

2.用于注入数据==property

@Autowired:
* 作用:自动按照类型注入,当容器中有唯一一个bean对象类型和要注入的变量类型匹配,就可以成功注入
* 使用位置:变量、方法
* 匹配过程:先用类型名称去ioc容器中圈出所有该类型对象,如果唯一则自动注入成功
如果ioc容器中有多个匹配对象时,再用变量名称id与容器中的key值(即component的value属性)进行匹配,匹配成功则注入成功,否则报错。

@Qualifier:
* 作用:在按照类型注入的基础上再按照名称注入。
在给类成员注入时不能单独使用,必须和@Autowired一起使用
在给方法注入时可以单独使用
* 属性:value:指定注入的bean对象id(即component的value属性)

@Resource
* 作用:直接按照bean对象的id注入。
* 属性:name:指定注入的bean对象id
* 使用该注解需要在pom.xml中添加以下依赖

    <dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
   </dependency>
  • 以上三个注解都只能用于其他bean类型数据的注入,而基本类型和String无法使用上述注解实现,
  • 集合类型只能通过xml实现

@Value
*作用:用于注入基本类型和String类型的数据
*属性:value:用于指定数据的值。它可以使用spring中SpEL(spring的el表达式)
SqEL的写法:$(表达式)

3.用于改变作用范围==scope属性

@Scope
* 作用:用于指定bean的作用范围
* 属性:value 常用取值为 singleton(默认取值), prototype

4.和生命周期相关==init-method="" 和 destroy-method=""

@PreDestroy
* 作用:指定销毁方法,spring不负责多例( @Scope(prototype))对象的销毁
@PostConstruct
* 作用:指定初始化方法

使用示例

@Scope(value ="prototype" )
@Component(value="accountService")
public class AccountServiceImpl implements IAccountService {
   @Autowired
   @Qualifier(value = "account1")
   private IAccountDao accountDao ;
  
   @Resource(name = "account2")
    private IAccountDao accountDao2 ;
  
   @Value("asbd")
   public String str;

    public AccountServiceImpl() {
        System.out.println("对象通过默认构造函数创建了");
    }

    @PostConstruct
    public void init(){
        System.out.println("对象初始化了");

    }
    @PreDestroy
    public  void destroy(){
        System.out.println("对象销毁了");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值