/**
* 位置类,用于描述学校的位置信息
*/
class Location{
private String country;
private String city;
// 省略set/get方法
// 省略toString方法
}
/**
* 学校信息
*/
public class School {
// 用于演示基本数据类型的注入
private String name;
// 学校位置,依赖于Location对象
private Location location;
// 用于演示集合类的注入
private List<String> teachers;
private Set<String> buildings;
private Map<String, String> departments;
public School() {
teachers = new ArrayList<>();
buildings = new HashSet<>();
departments = new HashMap<>();
}
// 用于演示构造器注入
public School(String name) {
this();
this.name = name;
}
// 省略set/get方法
// 省略toString方法
}
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--声明Location bean,并且为其两个属性注入对应的字面值-->
<bean id="location" class="cn.xuhuanfeng.domain.Location">
<property name="city" value="china"/>
<property name="country" value="ShenZhen"/>
</bean>
<!--配置School bean,并为其注入对象的属性-->
<bean id="school" class="cn.xuhuanfeng.domain.School">
<!--构造器注入 index用于指定所要注入的参数的位置,type用于指定注入的参数的类型-->
<constructor-arg index="0" type="java.lang.String" value="SZU"/>
<!--由于location依赖于Location对象,所以这里使用的是ref,用于表示引用另一个bean-->
<property name="location" ref="location"/>
<!--注入set内容-->
<property name="buildings">
<set>
<value>Domain A</value>
<value>Domain B</value>
<value>Domain C</value>
</set>
</property>
<!--注入list内容-->
<property name="teachers">
<list>
<value>Dr.Wang</value>
<value>Pro.Chen</value>
<value>Miss.Wu</value>
</list>
</property>
<!--注入map内容-->
<property name="departments">
<map>
<entry key="cs" value="Dr.ming"/>
<entry key="se" value="Dr.liu"/>
</map>
</property>
</bean>
</beans>
@Component
public class Location{
private String country;
private String city;
}
@Component
public class School {
@Value("SZU")
private String name;
@Autowired // 自动注入
private Location location;
// ....
}
<?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:p="http://www.springframework.org/schema/p"
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 http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启自动扫描, base-package指定所要扫描的包 -->
<context:component-scan base-package="cn.xuhuanfeng.domain" />
</beans>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有