Spring(七)用@Resource和@Autowired注解完成属性装配及自动装配

2024-06-16 11:08

本文主要是介绍Spring(七)用@Resource和@Autowired注解完成属性装配及自动装配,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用到注解需导入jar包:common-annotations.jar
手工装配依赖对象有两种编程方式:
一、在xml配置文件中通过bean节点进行配置,如:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean id="personDao" class="test.spring.dao.impl.PersonDaoBean" /><bean id="personService" class="test.spring.service.impl.PersonServiceBean3"><constructor-arg index="0" type="test.spring.dao.PersonDao" ref="personDao"/><constructor-arg index="1" value="LinDL"/></bean>
</beans> 

二、在Java代码中使用@Autowired或@Resource注解方式进行装配。但需在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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd"><!-- 把针对注解的容器注射到Spring容器中 --><context:annotation-config /><bean id="..." class="..." /></beans> 

这个配置隐式注册了多个对注释进行解析处理的处理器:AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor、RequireAnnotationBeanPostProcessor

在代码中使用@Autowired或@Resource注解方式进行装配,这两个注解的区别是:
@Autowired默认按类型装配,@Resource默认按名称装配,当找不到与名称匹配的bean才会按类型装配。
用于字段上
@Resource
private PersonDao personDao;
用于属性的setter方法上
@Resource
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}

一个应用@Resource的例子:

package test.spring.dao;public interface PersonDao {public abstract void add();}
package test.spring.dao.impl;import test.spring.dao.PersonDao;public class PersonDaoBean implements PersonDao {@Overridepublic void add(){System.out.println("执行PersonDaoBean里的test1()方法");}
}
package test.spring.service;public interface PersonService2 {public abstract void save();
}
package test.spring.service.impl;import javax.annotation.Resource;import test.spring.dao.PersonDao;
import test.spring.service.PersonService2;public class PersonServiceBean4 implements PersonService2 {// 先根据属性名personDao在beans2.xml中查找注入,如果找不到对应的就会按照类型进行注入// @Resource// private PersonDao personDao;// 也可以指定配置文件中的id进行注入// @Resource(name = "personDaoxx")private PersonDao personDao;public PersonServiceBean4() {}public PersonDao getPersonDao() {return personDao;}// 也可以通过属性的setter方法进行注入,不能用于属性的getter方法@Resourcepublic void setPersonDao(PersonDao personDao) {this.personDao = personDao;}@Overridepublic void save() {personDao.add();}
}

beans2.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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd"><!-- 把针对注解的容器注射到Spring容器中 --><context:annotation-config /><bean id="personDaoxx" class="test.spring.dao.impl.PersonDaoBean" /><bean id="personService" class="test.spring.service.impl.PersonServiceBean4"></bean>
</beans> 
package test.spring.jnit;import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import test.spring.service.PersonService2;public class SpringTest3 {@Testpublic void testInject() {AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans2.xml");PersonService2 personService = (PersonService2) applicationContext.getBean("personService");personService.save();applicationContext.close();}}

@Autowired的应用

package test.spring.service.impl;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;import test.spring.dao.PersonDao;
import test.spring.service.PersonService2;public class PersonServiceBean5 implements PersonService2 {// 按类型进行装配// @Autowired// private PersonDao personDao;// 按名称进行装配// @Autowired@Qualifier("personDaoxx")// private PersonDao personDao;/** required=true,如果在Spring中根据类型找不到对应的容器,就会报没有成功地为这个字段注入值;* required=false,如果在Spring容器里面找不到与类型匹配的bean,就会把这个变量设为null*/@Autowired(required = true)@Qualifier("personDaoxx")private PersonDao personDao;public PersonServiceBean5() {}public PersonDao getPersonDao() {return personDao;}public void setPersonDao(PersonDao personDao) {this.personDao = personDao;}@Overridepublic void save() {personDao.add();}
}

自动装配,使用自动装配方式难以调试,程序中的bug通常在运行过程中出现问题才发现,而且容易出现难以预料的问题,故不建议使用。
beans3.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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd"><bean id="personDaoxx" class="test.spring.dao.impl.PersonDaoBean" /><bean id="personService" class="test.spring.service.impl.PersonServiceBean6" autowire="byType"></bean></beans> 
package test.spring.service.impl;import test.spring.dao.PersonDao;
import test.spring.service.PersonService2;public class PersonServiceBean6 implements PersonService2 {private PersonDao personDao;public PersonServiceBean6() {}public void setPersonDao(PersonDao personDao) {this.personDao = personDao;}@Overridepublic void save() {personDao.add();}
}
package test.spring.jnit;import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import test.spring.service.PersonService2;public class SpringTest5 {@Testpublic void testAutowired() {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans3.xml");PersonService2 personService = (PersonService2) applicationContext.getBean("personService");personService.save();}}

这篇关于Spring(七)用@Resource和@Autowired注解完成属性装配及自动装配的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1066292

相关文章

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired

Spring 依赖注入与循环依赖总结

《Spring依赖注入与循环依赖总结》这篇文章给大家介绍Spring依赖注入与循环依赖总结篇,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. Spring 三级缓存解决循环依赖1. 创建UserService原始对象2. 将原始对象包装成工

Java中如何正确的停掉线程

《Java中如何正确的停掉线程》Java通过interrupt()通知线程停止而非强制,确保线程自主处理中断,避免数据损坏,线程池的shutdown()等待任务完成,shutdownNow()强制中断... 目录为什么不强制停止为什么 Java 不提供强制停止线程的能力呢?如何用interrupt停止线程s

SpringBoot请求参数传递与接收示例详解

《SpringBoot请求参数传递与接收示例详解》本文给大家介绍SpringBoot请求参数传递与接收示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录I. 基础参数传递i.查询参数(Query Parameters)ii.路径参数(Path Va

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp

Java MCP 的鉴权深度解析

《JavaMCP的鉴权深度解析》文章介绍JavaMCP鉴权的实现方式,指出客户端可通过queryString、header或env传递鉴权信息,服务器端支持工具单独鉴权、过滤器集中鉴权及启动时鉴权... 目录一、MCP Client 侧(负责传递,比较简单)(1)常见的 mcpServers json 配置

GSON框架下将百度天气JSON数据转JavaBean

《GSON框架下将百度天气JSON数据转JavaBean》这篇文章主要为大家详细介绍了如何在GSON框架下实现将百度天气JSON数据转JavaBean,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言一、百度天气jsON1、请求参数2、返回参数3、属性映射二、GSON属性映射实战1、类对象映

Java Stream 并行流简介、使用与注意事项小结

《JavaStream并行流简介、使用与注意事项小结》Java8并行流基于StreamAPI,利用多核CPU提升计算密集型任务效率,但需注意线程安全、顺序不确定及线程池管理,可通过自定义线程池与C... 目录1. 并行流简介​特点:​2. 并行流的简单使用​示例:并行流的基本使用​3. 配合自定义线程池​示

从原理到实战解析Java Stream 的并行流性能优化

《从原理到实战解析JavaStream的并行流性能优化》本文给大家介绍JavaStream的并行流性能优化:从原理到实战的全攻略,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的... 目录一、并行流的核心原理与适用场景二、性能优化的核心策略1. 合理设置并行度:打破默认阈值2. 避免装箱

解决升级JDK报错:module java.base does not“opens java.lang.reflect“to unnamed module问题

《解决升级JDK报错:modulejava.basedoesnot“opensjava.lang.reflect“tounnamedmodule问题》SpringBoot启动错误源于Jav... 目录问题描述原因分析解决方案总结问题描述启动sprintboot时报以下错误原因分析编程异js常是由Ja