Spring注入方式:
1.普通注入:
採用注入的方式可以在程序中不需要new對象而獲取已經註冊的對象
<!-- 將對象註冊到spring的容器原理 -->
<bean id="girl1" class="spring.bean.Girl">
<property name="name"><value>嶽好</value></property>
<property name="age"><value>24</value></property>
</bean>
ApplicationContext ctx=new ClassPathXmlApplicationContext(new String("applicationContext.xml"));
Girl girl=(Girl) ctx.getBean("girl1");
System.out.println(girl.getName()+girl.getAge());
//通過這個方法我們沒有通過對象來new,但卻獲取了一個對象
2.構造方法注入:
<!-- 通過構造函數來注入對象 -->
<bean id="girl2" class="spring.bean.Girl">
<constructor-arg type="java.lang.String" name="name"><value>范冰冰,12</value></constructor-arg>
<constructor-arg type="int" name="age" ><value>100</value></constructor-arg>
</bean>
Girl girl2=(Girl) ctx.getBean("girl2", Girl.class);
System.out.println(girl2.getName()+girl2.getAge());
3.集合注入:
<!-- 屬性中注入集合數據 -->
<bean id="girl3" class="spring.bean.Girl">
<property name="name" value="鵬翔"></property>
<property name="hobbys">
<list><value>喫飯</value><value>睡覺</value></list>
</property>
<property name="age"><value>23</value></property>
</bean>
Girl girl3=(Girl) ctx.getBean("girl3", Girl.class);
System.out.println(girl3.getName()+girl3.getAge());
for(String hobby:girl3.getHobbys()){
System.out.println(hobby);
}
4.鍵值對注入:
<bean id="girl4" class="spring.bean.Girl">
<property name="name" value="傻狍子"></property>
<property name="hobbys">
<list><value>喫飯</value><value>睡覺</value></list>
</property>
<property name="age"><value>23</value></property>
<property name="score">
<map>
<entry>
<key><value>語文</value></key><value>100</value>
</entry>
<entry>
<key><value>數學</value></key><value>120</value>
</entry>
</map>
</property>
</bean>
迭代器遍歷
Girl girl4=ctx.getBean("girl4",Girl.class);
Set<String> sets=girl4.getScore().keySet();
Iterator<String> keyits=sets.iterator();
while(keyits.hasNext()){
String key=keyits.next();
int value=girl4.getScore().get(key);
System.out.println(" 分數 "+value);
}
5.引用注入:引用其他bean
<bean id="boy1" class="spring.bean.Boy"><!-- 引用其他的bean對象 -->
<property name="name" ><value>鵬翔</value></property>
<property name="girl" ref="girl4"></property><!-- 他要找的對象是在這個表裏註冊的對象 ref 來使用-->
</bean>
ApplicationContext ctx=new ClassPathXmlApplicationContext(new String("applicationContext.xml"));
Boy boy1=(Boy)ctx.getBean("boy1", Boy.class);
System.out.println(boy1.getName()+boy1.getGirl().getName());
6.自動裝配
爲了解決bean過多導致混淆