SSH框架之Spring注入

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过多导致混淆

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

彭祥.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值