Attempt-Spring-2 笔记:

 Attempt-Spring-2 笔记:

 

 

1、 内部bean 的使用;

 

Bean配置;

 

<!-- 配置内部bean -->

    

    <bean id="per1" class="qau.edu.Person" p:name="罗斯" p:age="34">

    

       <property name="books">

          <bean class="qau.edu.Books" p:number="10003" p:page="56">

          

            <property name="name">

              <value><![CDATA[《陆犯焉识》]]></value>

            </property>

          

          </bean>

       </property>

    

    </bean>

 

这样的我认为就是属于内部的引用吧、、、

 

 

2、 自动装配:

 

代码:

 

配置文件:

 

 

 

<?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:p="http://www.springframework.org/schema/p"

   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

 

<!-- 配置自动装配 bean  -->

 

<bean id="city" class="qau.edu.City" p:name="滨州市" p:num="0543"></bean>

 

<bean id="book" class="qau.edu.Book" p:page="3334" p:price="66.45">

   <property name="name">

     <value><![CDATA[《Java EE》]]></value>

   </property>

</bean>

 

<bean id="person" class="qau.edu.Person" p:name="任建勇" p:book-ref="book" p:city-ref="city" p:sex="男"></bean>

 

 

<!-- 使用自动装配方式 -->

 

<bean id="per2" class="qau.edu.Person" p:name="乔丹" p:sex="男" autowire="byName"></bean>

 

</beans>

 

 

上面是进行了传统的手工的装配和自动装配;

 

byname:根据名字进行自动装配,这里的名字就是(以上面的例子为例),Person中的Citybook属性名字和 setter 方法中的名字相同,也就是SetXxxz中的Xxx

byType:根据类型进行自动装配,但是这样的方式是不能允许出现同样类型的多个对象,只允许一个;

 

测试类:

 

package qau.edu;

 

import org.junit.Test;

import org.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Rentest {

 

   @Test

   public void test() {

     

//    创建applicationcontext对象;

     

      ApplicationContext ctx = new ClassPathXmlApplicationContext("Ren.xml");

     

//    获取对象;

     

//    City city = (City) ctx.getBean("city");

//   

//    Book book = (Book) ctx.getBean("book");

     

      Person per = (Person) ctx.getBean("person");

     

      Person per2 = (Person) ctx.getBean("per2");

     

//    输出;

     

//    System.out.println(city);

//    System.out.println(book);

      System.out.println(per);

      System.out.println(per2);

   }

 

}

 

 

 

 

 

3、 继承关系:

 

代码:

(传统的实现)

<!-- bean 之间的关系 (继承关系)-->

  

   <bean id="book1" class="qau.edu.Book" p:page="232" p:price="34.4">

    

     <property name="name">

       <value><![CDATA[《呼啸山庄》]]></value>

     </property>

    

   </bean>

  

   <bean id="book2" class="qau.edu.Book" p:page="2432" p:price="3423.4">

    

     <property name="name">

       <value><![CDATA[《平凡的世界》]]></value>

     </property>

    

   </bean>

 

测试类;

 

// bean之间的关系;

  

   @Test

   public void test2() {

     

//    创建applicationcontext对象;

     

      ApplicationContext ctx = new ClassPathXmlApplicationContext("Ren.xml");

     

//    获取对象;

     

     

      Book book = (Book) ctx.getBean("book1");

     

      Book book2 = (Book) ctx.getBean("book2");

     

//    输出;

     

     

      System.out.println(book);

      System.out.println(book2);

     

   }

 

 

设置继承关系:

 

<!-- bean 之间的关系 (继承关系)-->

  

   <bean id="book1" class="qau.edu.Book" p:page="232" p:price="34.4">

    

     <property name="name">

       <value><![CDATA[《呼啸山庄》]]></value>

     </property>

    

   </bean>

  

   <bean id="book2" class="qau.edu.Book" parent="book1">

    

     <property name="name">

       <value><![CDATA[《平凡的世界》]]></value>

     </property>

    

   </bean>

 

这是修改之后的bean 但是同样的测试类之下,结果是相同的。

 

继续修改:

 

<!-- bean 之间的关系 (继承关系)-->

  

   <bean id="book1"  p:page="232" p:price="34.4" abstract="true">

    

     <property name="name">

       <value><![CDATA[《呼啸山庄》]]></value>

     </property>

    

   </bean>

  

   <bean id="book2" class="qau.edu.Book" parent="book1">

    

     <property name="name">

       <value><![CDATA[《平凡的世界》]]></value>

     </property>

    

   </bean>

 

总结:

 

上面的第一种修改是利用的<parent> 属性,进行bean 之间的继承,这里的继承是区分Java中的继承的,这是一种属性上的继承,继承的叫做子bean ,被继承的叫做父bean ,子bean能覆盖父 bean的属性值;第二种修改是通过<abstract>属性,把bean变成抽象的,这样是不能在IOC容器中进行实例化的,这一点很像Java,这样的bean既然不能进行实例化,那样就没有必要进行指定路径,这种抽象就是一种进行复制或者是大量生产的模板。

 

 

4、 依赖关系:

 

 

   <!-- bean之间的关系(依赖关系) -->

  

   <bean id="per3" class="qau.edu.Person" p:name="任建勇" p:sex="男" depends-on="per2"></bean>

 

 

上面的这种依赖关系换句话说就是:必须要有这个bean,比如上面例子中,< depends-on="per2">

的含义就是必须要求有per2这个bean

 

 

 

 

5、 bean的作用域:

 

代码:

 

<!--bean中的作用域  -->

   

   <bean id="book3" class="qau.edu.Book" p:price="34.9" p:page="23">

   

      <property name="name">

          <value><![CDATA[《京华烟雨》]]></value>

      </property>

     

   </bean>                    

 

 

测试类:

 

/*

    * bean的作用域:

    *

    *

    * */

  

   @Test

   public void testScope() {

     

//    创建applicationcontext对象;

     

      ApplicationContext ctx = new ClassPathXmlApplicationContext("Ren.xml");

     

//    获取对象;

     

      Book book = (Book) ctx.getBean("book3");

//   

      Book book2 = (Book) ctx.getBean("book3");

     

//    输出;

     

     

//   

      System.out.println(book);

      System.out.println(book2);

     

}

 

 

执行结果:

 

 

十一月 23, 2014 5:50:20 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh

信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@13ac14d: startup date [Sun Nov 23 17:50:20 CST 2014]; root of context hierarchy

十一月 23, 2014 5:50:21 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

信息: Loading XML bean definitions from class path resource [Ren.xml]

Book`s  constructor、、、、、、

Book [name=《京华烟雨》, page=23, price=34.9]

Book [name=《京华烟雨》, page=23, price=34.9]

 

 

 

 

(当时为了测试方便和进行比较,在Book.java中加入了显式的没有参数的构造方法)

 

上面是默认的scopesingleto;也就是单例的;

 

代码:

 

<!--bean中的作用域  -->

   

   <bean id="book3" class="qau.edu.Book" p:price="34.9" p:page="23" scope="prototype">

   

      <property name="name">

          <value><![CDATA[《京华烟雨》]]></value>

      </property>

     

   </bean>         

 

测试类不变:

执行结果:

 

十一月 23, 2014 5:58:49 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh

信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@13ac14d: startup date [Sun Nov 23 17:58:49 CST 2014]; root of context hierarchy

十一月 23, 2014 5:58:49 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

信息: Loading XML bean definitions from class path resource [Ren.xml]

Book`s  constructor、、、、、、

Book`s  constructor、、、、、、

 

Book [name=《京华烟雨》, page=23, price=34.9]

Book [name=《京华烟雨》, page=23, price=34.9]

 

 

 

比较上面的两种结果就能知道:

默认情况之下是单例的bean也就是说在进行applicationcontext实例化的时候,就已经进行初始化,这是IOC容器帮助进行的,而且假如是同类的需要多个相同对象,只是创建一次,重复使用。但是scope=prototype的时候,就不再是单例的,而是不管不是不同类的对象,需要几个就进行几次创建,并不是在applicationcontext创建时候进行的实例化。

 

还能直观的观察:

 

代码:

 

Scope=singleto:

 

十一月 23, 2014 6:07:38 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh

信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@11a2576: startup date [Sun Nov 23 18:07:38 CST 2014]; root of context hierarchy

十一月 23, 2014 6:07:38 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

信息: Loading XML bean definitions from class path resource [Ren.xml]

Book`s  constructor、、、、、、

 

 

 

Scope=prototype:

 

十一月 23, 2014 6:09:14 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh

信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@11a2576: startup date [Sun Nov 23 18:09:14 CST 2014]; root of context hierarchy

十一月 23, 2014 6:09:14 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

信息: Loading XML bean definitions from class path resource [Ren.xml]

Book`s  constructor、、、、、、

Book`s  constructor、、、、、、

 

 

 

这样就更加直接能看出来了、、、、

 

 

 

6、 使用外部属性文件;

 

 

代码:

 

<?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"

   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

 

    <!-- 导入外部属性文件 -->

    

    <context:property-placeholder location="classpath:ren"/>

 

   <!--配置数据源 -->

 

   <bean id="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

  

    <!-- 使用外部属性文件 -->

    

      <property name="user" value="${user}"></property>

      <property name="password" value="${password}"></property>

      <property name="driverClass" value="${driverClass}"></property>

      <property name="jdbcUrl" value="${jdbcUrl}"></property>

 

   </bean>

 

</beans>

 

 

 

测试类代码:

 

package qau.edu.properties;

 

 

import java.sql.SQLException;

 

import javax.sql.DataSource;

 

import org.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Main {

  

   public static void main(String[] args) throws SQLException {

     

//    创建ApplicationContext;

  

      ApplicationContext ctx = new ClassPathXmlApplicationContext("properties.xml");

     

//    获取对象;

     

      DataSource data = (DataSource) ctx.getBean("dataSource");

     

//    输出结果;

     

      System.out.println(data.getConnection());

     

   }

 

 

  

  

}

 

 

 

执行结果:

 

十一月 23, 2014 7:37:58 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh

信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@cbd8dc: startup date [Sun Nov 23 19:37:58 CST 2014]; root of context hierarchy

十一月 23, 2014 7:37:58 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

信息: Loading XML bean definitions from class path resource [properties.xml]

十一月 23, 2014 7:37:59 下午 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties

信息: Loading properties file from class path resource [ren]

十一月 23, 2014 7:37:59 下午 com.mchange.v2.log.MLog <clinit>

信息: MLog clients using java 1.4+ standard logging.

十一月 23, 2014 7:37:59 下午 com.mchange.v2.c3p0.C3P0Registry banner

信息: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]

十一月 23, 2014 7:37:59 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager

信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge5fl951p5ydp0j3gmi|148ff04, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge5fl951p5ydp0j3gmi|148ff04, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql:///test, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]

com.mchange.v2.c3p0.impl.NewProxyConnection@16cc7c7

 

 

 

这个例子这是进行的数据源的配置;

 

 

7、 关于spEL

 

这是类似于EL表达式的;

 

 

 

代码:

 

配置文件:

 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

 

   <bean id="book" class="qau.edu.SpEL.Book">

 

      <property name="name">

         <value><![CDATA[《苏菲的世界》]]></value>

      </property>

      <property name="page" value="#{2333}"></property>

      <property name="price" value="#{T(java.lang.Math).PI * 23}"></property>

     

   </bean>

  

   <bean id="city" class="qau.edu.SpEL.City">

  

     <property name="name" value="滨州市"></property>

     <property name="num" value="#{0543}"></property>

    

   </bean>

 

     

    <bean id="per" class="qau.edu.SpEL.Person">

      <property name="name" value="任建勇"></property>

      <property name="sex" value="男"></property>

      <property name="city" value="#{city.name}"></property>

      <property name="iden" value="#{book.page > 20 ? '经典' : '废物'}"></property>

      <property name="age" value="21"></property>

    </bean>

 

 

</beans>

 

 

 

测试编码:

 

package qau.edu.SpEL;

 

import org.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Main {

 

   public static void main(String[] args) {

     

//    创建ApplicationContext;

     

      ApplicationContext ctx = new ClassPathXmlApplicationContext("spel.xml");

     

//    获取对象;

     

      Book book = (Book) ctx.getBean("book");

      City city = (City) ctx.getBean("city");

      Person per = (Person) ctx.getBean("per");

     

//    输出结果;

     

      System.out.println(book);

      System.out.println(city);

      System.out.println(per);

   }

}

 

 

 

执行结果:

 

 

十一月 23, 2014 8:28:03 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh

信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5dfaf1: startup date [Sun Nov 23 20:28:03 CST 2014]; root of context hierarchy

十一月 23, 2014 8:28:04 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

信息: Loading XML bean definitions from class path resource [spel.xml]

Book`s  constructor、、、、、、

book`s  setter、、、、

Book [name=《苏菲的世界》, page=2333, price=72.25663103256524]

City : [num=543, name=滨州市]

Person [name=任建勇, sex=男, city=滨州市, iden=经典, age=21]

 

 

在上面的演示中展示了spEL的广泛的使用:运算符使用、字面值使用、静态属性的使用、逻辑运算符的使用、引用的使用、、、很方便的机制。

 

 

8、 使用工厂方式进行 bean 的配置:

 

1)、静态工厂:

 

 

代码:

 

一般类:

 

package qau.edu.staticFactory;

 

public class Book {

 

   private  String name ;

  

   private int page ;

  

   private double price ;

 

   public Book(String name, int page, double price) {

      super();

      this.name = name;

      this.page = page;

      this.price = price;

   }

 

   public Book() {

      super();

   }

 

   @Override

   public String toString() {

      return "Book [name=" + name + ", page=" + page + ", price=" + price

            + "]";

   }

}

 

 

配置文件:

 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

 

 

<!-- 配置静态工厂方式文件 -->

 

   <bean id="book" class="qau.edu.staticFactory.StaticFactory"

      factory-method="getBook">

     

      <constructor-arg value="AA"></constructor-arg>

   </bean>

  

</beans>

 

 

Class:表示的是静态方法的那个类的路径;

 

factory-method:表示的是类中提供的获取对象的静态方法;

 

constructor-arg:表示的是类中提供的获取对象的静态方法中提供的获取对象的依据。

 

测试代码:

 

package qau.edu.staticFactory;

 

import org.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Main {

 

   public static void main(String[] args) {

     

//    创建ApplicationContext对象;

     

      ApplicationContext ctx = new ClassPathXmlApplicationContext("staticFactory.xml");

     

//    获取对象;

     

      Book book = (Book) ctx.getBean("book");

     

//    输出结果;

     

      System.out.println(book);

     

   }

}

 

 

 

 

执行结果:

 

十一月 23, 2014 9:15:00 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh

信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1b5391b: startup date [Sun Nov 23 21:15:00 CST 2014]; root of context hierarchy

十一月 23, 2014 9:15:00 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

信息: Loading XML bean definitions from class path resource [staticFactory.xml]

Book [name=《基督山伯爵》, page=233, price=23.4]

 

 

 

2)、实例工厂:{先实例化工厂再通过工厂进行对象的获取}

 

代码:

 

package qau.edu.staticFactory;

 

import java.util.HashMap;

import java.util.Map;

 

public class StaticFactory {

 

   private static Map<String,Book> books = new HashMap<>();

  

   static{

     

      books.put("AA"new Book("《基督山伯爵》",233,23.4));

      books.put("BB"new Book("《复活》",234,25.4));

     

   }

  

   public static Book getBook(String name){

     

      return books.get(name);

     

   }

  

}

 

 

 

配置文件:

 

<!-- 配置实力工厂方式 -->

  

   <!-- 配置实例工厂的方式 -->

  

   <bean id="instant" class="qau.edu.staticFactory.instantFactory"></bean>

  

   <!-- 配置通过实例工厂获取对象 -->

  

   <bean id="book2" factory-bean="instant" factory-method="getBook">

     <constructor-arg value="AA"></constructor-arg>

   </bean>

 

 

执行结果:

 

十一月 23, 2014 9:43:17 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh

信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@b85c17: startup date [Sun Nov 23 21:43:17 CST 2014]; root of context hierarchy

十一月 23, 2014 9:43:17 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

信息: Loading XML bean definitions from class path resource [staticFactory.xml]

Book [name=《基督山伯爵》, page=233, price=23.4]

Book [name=《活着》, page=233323, price=344.5]

 

 

 

 

如果没有一直坚持,也不会有质的飞跃,当生命有了限度,每个人的价值就会浮现。
原文地址:https://www.cnblogs.com/shiguangshuo/p/4117545.html