Spring——依赖注入

1.构造器注入

前面已经有了

 

2.Set方式注入【重点】

  • 依赖注入:set注入

    • 依赖:bean对象的创建依赖于容器

    • 注入:bean对象中的所有属性由容器来注入

【环境搭建】

1.测试类型

private String name;
private Address address;//另一个实体类,务必重写toString方法
private String[] books;
private List<String> hobbies;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;

测试类要加上toString方法

2.beans.xml

<bean id="address" class="com.yl.pojo.Address">
   <property name="address" value="zufe"/>
</bean>

<bean id="student" class="com.yl.pojo.Student">
   <!--普通值注入:直接使用value-->
   <property name="name" value="撸撸"/>
   <!--bean注入:使用ref,对应最上方的bean标签-->
   <property name="address" ref="address"/>
   <!--数组注入-->
   <property name="books">
       <array>
           <value>《红楼梦》</value>
           <value>《西游记》</value>
           <value>《水浒传》</value>
       </array>
   </property>
   <!--list注入-->
   <property name="hobbies">
       <list>
           <value>听歌</value>
           <value>编程</value>
           <value>逛街</value>
       </list>
   </property>
   <!--map注入-->
   <property name="card">
       <map>
           <entry key="身份证" value="11111111111111111111"/>
           <entry key="银行卡" value="22222222222222222222"/>
       </map>
   </property>
   <!--set注入-->
   <property name="games">
       <set>
           <value>cube escape</value>
           <value>rusty lake</value>
       </set>
   </property>
   <!--空值注入-->
   <property name="wife">
       <null/>
   </property>
   <!--properties注入-->
   <property name="info">
       <props>
           <prop key="学号">1234</prop>
           <prop key="性别">女</prop>
       </props>
   </property>
</bean>

 

3.扩展方式注入

p命名空间

<beans>中导入约束

xmlns:p="http://www.springframework.org/schema/p"

注入:

<!--p命名空间注入,可以直接注入属性的值-->
<bean id="user" class="com.yl.pojo.User" p:name="撸撸" p:age="18"/>

 

c命名空间注入

<beans>中导入约束

xmlns:c="http://www.springframework.org/schema/c"

注入:

<!--c命名空间注入,通过有参构造器注入-->
<bean id="user2" class="com.yl.pojo.User" c:age="21" c:name="lulu"/>

 

4.bean的作用域

1.单例模式(Spring默认机制):每次都获取的是同一个对象

<bean id="user2" class="com.yl.pojo.User" c:age="21" c:name="lulu" scope="singleton"/>

测试结果为true:

@Test
public void test2(){
   ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
   User user2 = context.getBean("user2", User.class);
   User user3 = context.getBean("user2", User.class);
   System.out.println(user2==user3);
}

 

2.原型模式:每次从容器中get的时候,都会产生一个新对象

<bean id="user2" class="com.yl.pojo.User" c:age="21" c:name="lulu" scope="prototype"/>

测试结果为false

 

3.其余的request、session,application这些只能在web开发中使用到

posted @ 2020-09-01 19:39  Fabulo  阅读(204)  评论(0)    收藏  举报