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

猜你喜欢

转载自blog.csdn.net/pengxiang1998/article/details/105517843
今日推荐