Hero 類只需要提供屬性和toString()方法,此處提供註解實現DI,所以不用寫get,set方法
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* 註解方式不需要get ,set
* @author wyy
* @date 2020/6/28 15:39
*/
@Component
public class Hero {
@Value("張三")
private String name;
@Value("18")
private int age;
@Value("#{l}")
private List<String> list;
@Value("#{s}")
private Set<String> set;
@Value("#{m}")
private Map<String,String> map;
@Value("#{p}")
private Properties prop;
@Override
public String toString() {
return "Hero{" +
"name='" + name + '\'' +
", age=" + age +
", list=" + list +
", set=" + set +
", map=" + map +
", prop=" + prop +
'}';
}
}
web.xm中的配置
注意:
- 當set中出現重複值時,spring容器會自動剔除
- 當map中出現重複的key時,spring容器會自動剔除
- 當properties中出現重複的key時,spring容器會自動剔除
<context:annotation-config/> 這個是註解方式實現DI,可以不用get\set方法,開啓即可,相當於一個開關,一定要給一個字符串,當值是int時可以寫爲@Value("18"),spring會自動轉換
<?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"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
<!--配置包掃描-->
<context:component-scan base-package="cn.tedu.domains"/>
<!--註解方式DI,可以不用get\set方法-->
<context:annotation-config/>
<!--預配置數據-->
<util:list id="l">
<value>l1</value>
<value>l2</value>
</util:list>
<util:set id="s">
<value>s1</value>
<value>s1</value>
<value>s2</value>
</util:set>
<!--map會自動去重-->
<util:map id="m">
<entry key="k1" value="v1"/>
<entry key="k2" value="v2"/>
<entry key="k1" value="v1"/>
<entry key="k3" value="v1"/>
</util:map>
<!--properties會自動去重-->
<util:properties id="p" >
<prop key="p1">v1</prop>
<prop key="p1">v1</prop>
<prop key="p2">v1</prop>
<prop key="p3">v3</prop>
</util:properties>
</beans>
測試類:
import cn.tedu.domains.Hero;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
Hero hero = (Hero) context.getBean("hero");
System.out.println(hero);
((ClassPathXmlApplicationContext)context).close();
}
}
測試結果: