Spring - 属性注入 5 种方式(XML)

简介: Spring - 属性注入 5 种方式(XML)

image.pngimage.png

packagecom.imooc.ioc.demo4;
publicclassUser {
privateStringname;
privateIntegerage;
publicUser(Stringname,Integerage){
this.name=name;
this.age=age;
    }
@OverridepublicStringtoString() {
return"User{"+"name='"+name+'\''+", age="+age+'}';
    }
}
<!--Bean的构造方法的属性注入--><beanid="user"class="com.imooc.ioc.demo4.User"><constructor-argname="name"value="张三"/><constructor-argname="age"value="23"/></bean>
packagecom.imooc.ioc.demo4;
importorg.junit.Test;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassSpringDemo4 {
@Testpublicvoiddemo1(){
ApplicationContextapplicationContext=newClassPathXmlApplicationContext("applicationContext.xml");
Useruser= (User)applicationContext.getBean("user");
System.out.println(user);
    }
}
运行结果:User{name='张三', age=23}

image.pngPs:普通的用 value,bean用 ref。

packagecom.imooc.ioc.demo4;
publicclassPerson {
privateStringname;
privateIntegerage;
privateCatcat;
publicStringgetName() {
returnname;
    }
publicvoidsetName(Stringname) {
this.name=name;
    }
publicIntegergetAge() {
returnage;
    }
publicvoidsetAge(Integerage) {
this.age=age;
    }
publicCatgetCat() {
returncat;
    }
publicvoidsetCat(Catcat) {
this.cat=cat;
    }
@OverridepublicStringtoString() {
return"Person{"+"name='"+name+'\''+", age="+age+", cat="+cat+'}';
    }
}
packagecom.imooc.ioc.demo4;
publicclassCat {
privateStringname;
publicStringgetName() {
returnname;
    }
publicvoidsetName(Stringname) {
this.name=name;
    }
@OverridepublicStringtoString() {
return"Cat{"+"name='"+name+'\''+'}';
    }
}
<!--Bean的set方法的属性注入--><beanid="person"class="com.imooc.ioc.demo4.Person"><propertyname="name"value="李四"/><propertyname="age"value="32"/><propertyname="cat"ref="cat"/></bean><beanid="cat"class="com.imooc.ioc.demo4.Cat"><propertyname="name"value="ketty"/></bean>
packagecom.imooc.ioc.demo4;
importorg.junit.Test;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassSpringDemo4 {
@Testpublicvoiddemo2(){
ApplicationContextapplicationContext=newClassPathXmlApplicationContext("applicationContext.xml");
Personperson= (Person)applicationContext.getBean("person");
System.out.println(person);
    }
}
运行结果:Person{name='李四', age=32, cat=Cat{name='ketty'}}

image.png

<!--Bean的p名称空间的属性注入--><beanid="person"class="com.imooc.ioc.demo4.Person"p:name="大黄"p:age="34"p:cat-ref="cat"/><beanid="cat"class="com.imooc.ioc.demo4.Cat"p:name="小黄"/>
运行结果:Person{name='大黄', age=34, cat=Cat{name='小黄'}}

image.png

packagecom.imooc.ioc.demo4;
publicclassCategory {
privateStringname;
publicStringgetName() {
returnname;
    }
publicvoidsetName(Stringname) {
this.name=name;
    }
@OverridepublicStringtoString() {
return"Category{"+"name='"+name+'\''+'}';
    }
}
packagecom.imooc.ioc.demo4;
publicclassProduct {
privateStringname;
privateDoubleprice;
privateCategorycategory;
publicStringgetName() {
returnname;
    }
publicvoidsetName(Stringname) {
this.name=name;
    }
publicDoublegetPrice() {
returnprice;
    }
publicvoidsetPrice(Doubleprice) {
this.price=price;
    }
publicCategorygetCategory() {
returncategory;
    }
publicvoidsetCategory(Categorycategory) {
this.category=category;
    }
@OverridepublicStringtoString() {
return"Product{"+"name='"+name+'\''+", price="+price+", category="+category+'}';
    }
}
packagecom.imooc.ioc.demo4;
publicclassProductInfo {
publicDoublecalculatePrice(){
returnMath.random() *199;
    }
}
<!--Bean的SpEL的属性注入--><beanid="category"class="com.imooc.ioc.demo4.Category"><propertyname="name"value="#{'服装'}"/></bean><beanid="productInfo"class="com.imooc.ioc.demo4.ProductInfo"/><beanid="product"class="com.imooc.ioc.demo4.Product"><propertyname="name"value="#{'男装'}"/><propertyname="price"value="#{productInfo.calculatePrice()}"/><propertyname="category"value="#{category}"/></bean>
packagecom.imooc.ioc.demo4;
importorg.junit.Test;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassSpringDemo4 {
@Testpublicvoiddemo3(){
ApplicationContextapplicationContext=newClassPathXmlApplicationContext("applicationContext.xml");
Productproduct= (Product)applicationContext.getBean("product");
System.out.println(product);
    }
}
运行结果:Product{name='男装', price=155.43113186211818, category=Category{name='服装'}}

image.png

packagecom.imooc.ioc.demo5;
importjava.util.*;
publicclassCollectionBean {
privateString[] arrs; // 数组类型privateList<String>list; // List集合类型privateSet<String>set; // Set集合类型privateMap<String,Integer>map; // Map集合类型privatePropertiesproperties; // 属性类型publicString[] getArrs() {
returnarrs;
    }
publicvoidsetArrs(String[] arrs) {
this.arrs=arrs;
    }
publicList<String>getList() {
returnlist;
    }
publicvoidsetList(List<String>list) {
this.list=list;
    }
publicSet<String>getSet() {
returnset;
    }
publicvoidsetSet(Set<String>set) {
this.set=set;
    }
publicMap<String, Integer>getMap() {
returnmap;
    }
publicvoidsetMap(Map<String, Integer>map) {
this.map=map;
    }
publicPropertiesgetProperties() {
returnproperties;
    }
publicvoidsetProperties(Propertiesproperties) {
this.properties=properties;
    }
@OverridepublicStringtoString() {
return"CollectionBean{"+"arrs="+Arrays.toString(arrs) +", list="+list+", set="+set+", map="+map+", properties="+properties+'}';
    }
}
<!--集合类型的属性注入--><beanid="collectionBean"class="com.imooc.ioc.demo5.CollectionBean"><!--数组类型--><propertyname="arrs"><list><value>aaa</value><value>bbb</value><value>ccc</value></list></property><!--List集合的属性注入--><propertyname="list"><list><value>111</value><value>222</value><value>333</value></list></property><!--Set集合的属性注入--><propertyname="set"><set><value>ddd</value><value>eee</value><value>fff</value></set></property><!--Map集合的属性注入--><propertyname="map"><map><entrykey="aaa"value="111"/><entrykey="bbb"value="222"/><entrykey="ccc"value="333"/></map></property><!--Properties的属性注入--><propertyname="properties"><props><propkey="username">root</prop><propkey="password">1234</prop></props></property></bean>
packagecom.imooc.ioc.demo5;
importorg.junit.Test;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassSpringDemo5 {
@Testpublicvoiddemo1(){
ApplicationContextapplicationContext=newClassPathXmlApplicationContext("applicationContext.xml");
CollectionBeancollectionBean= (CollectionBean)applicationContext.getBean("collectionBean");
System.out.println(collectionBean);
    }
}
运行结果:CollectionBean{arrs=[aaa, bbb, ccc], list=[111, 222, 333], set=[ddd, eee, fff], map={aaa=111, bbb=222, ccc=333}, properties={password=1234, username=root}}
目录
打赏
0
0
0
0
37
分享
相关文章
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— logback.xml 配置文件解析
本文解析了 `logback.xml` 配置文件的详细内容,包括日志输出格式、存储路径、控制台输出及日志级别等关键配置。通过定义 `LOG_PATTERN` 和 `FILE_PATH`,设置日志格式与存储路径;利用 `&lt;appender&gt;` 节点配置控制台和文件输出,支持日志滚动策略(如文件大小限制和保存时长);最后通过 `&lt;logger&gt;` 和 `&lt;root&gt;` 定义日志级别与输出方式。此配置适用于精细化管理日志输出,满足不同场景需求。
162 1
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
65 0
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
35 0
Spring从入门到入土(xml配置文件的基础使用方式)
本文详细介绍了Spring框架中XML配置文件的使用方法,包括读取配置文件、创建带参数的构造对象、使用工厂方法和静态方法创建对象、对象生命周期管理以及单例和多例模式的测试。
277 7
Spring从入门到入土(xml配置文件的基础使用方式)
在使用Spring的`@Value`注解注入属性值时,有一些特殊字符需要注意
【10月更文挑战第9天】在使用Spring的`@Value`注解注入属性值时,需注意一些特殊字符的正确处理方法,包括空格、引号、反斜杠、新行、制表符、逗号、大括号、$、百分号及其他特殊字符。通过适当包裹或转义,确保这些字符能被正确解析和注入。
433 3
为什么Spring不推荐@Autowired用于字段注入?
作为Java程序员,Spring框架在日常开发中使用频繁,其依赖注入机制带来了极大的便利。然而,尽管@Autowired注解简化了依赖注入,Spring官方却不推荐在字段上使用它。本文将探讨字段注入的现状及其存在的问题,如难以进行单元测试、违反单一职责原则及易引发NPE等,并介绍为何Spring推荐构造器注入,包括增强代码可读性和维护性、方便单元测试以及避免NPE等问题。通过示例代码展示如何将字段注入重构为构造器注入,提高代码质量。
167 1
【SpringFramework】Spring IoC-基于XML的实现
本文主要讲解SpringFramework中IoC和DI相关概念,及基于XML的实现方式。
139 69
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——指定项目配置文件
在实际项目中,开发环境和生产环境的配置往往不同。为简化配置切换,可通过创建 `application-dev.yml` 和 `application-pro.yml` 分别管理开发与生产环境配置,如设置不同端口(8001/8002)。在 `application.yml` 中使用 `spring.profiles.active` 指定加载的配置文件,实现环境快速切换。本节还介绍了通过配置类读取参数的方法,适用于微服务场景,提升代码可维护性。课程源码可从 [Gitee](https://gitee.com/eson15/springboot_study) 下载。
58 0
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
在微服务架构中,随着业务复杂度增加,项目可能需要调用多个微服务。为避免使用`@Value`注解逐一引入配置的繁琐,可通过定义配置类(如`MicroServiceUrl`)并结合`@ConfigurationProperties`注解实现批量管理。此方法需在配置文件中设置微服务地址(如订单、用户、购物车服务),并通过`@Component`将配置类纳入Spring容器。最后,在Controller中通过`@Resource`注入配置类即可便捷使用,提升代码可维护性。
39 0
使用idea中的Live Templates自定义自动生成Spring所需的XML配置文件格式
本文介绍了在使用Spring框架时,如何通过创建`applicationContext.xml`配置文件来管理对象。首先,在resources目录下新建XML配置文件,并通过IDEA自动生成部分配置。为完善配置,特别是添加AOP支持,可以通过IDEA的Live Templates功能自定义XML模板。具体步骤包括:连续按两次Shift搜索Live Templates,配置模板内容,输入特定前缀(如spring)并按Tab键即可快速生成完整的Spring配置文件。这样可以大大提高开发效率,减少重复工作。
使用idea中的Live Templates自定义自动生成Spring所需的XML配置文件格式
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等