Spring 初探(三)(Spring bean 基本概念)

来源:互联网 发布:数据库建模谁来做 编辑:程序博客网 时间:2024/04/29 11:13
Uploading Files
java中常用的异常构造一般包含message(String) 及cause(Throwable)
后者声明导致此异常抛出的异常,由于Throwable为Error及Exception
的基类,故cause使用此作为参数类型。


由于对于spring所使用的bean不太了解,故现结合tutorialspoint
learn Spring进行简要介绍,阿三开的网站真牛,什么都有。
个人认为最为牛逼的一点是它提供了各种编译环境,甚至包含
python科学计算环境numpy scipy甚至C++11 R语言等比较冷门
的语言,这对于掌握多种语言的程序员十分地方便。
对于一些尝试性的工作不必配置环境,唯一的缺点就是可能比较慢。


这里不对具体内容进行介绍,仅仅是概括性的叙述,相应细节参看网站。


spring bean最基本的就是对某些特殊类指定属性值的值在xml文件的方法,
故可以看成一种配置。


spring bean的诸配置属性基本上赋予了container类似于类的属性(如 initialization method
destuction method等)
通过为bean指定init及destroy属性为相应类的方法名即可完成指定。
当要使得析构部分(destory)生效,需要对相应的bean类调用registerShutdownHook方法。
当有若干要进行初始化及析构的类时,可以在beans中对defaullt-init-method及
default-destroy-method属性指定方法名,这时可以进行统一的构造和析构。
虽然java也有finalize方法作为析构,但是不常用。
bean当不具有所需要设定的属性时,可以不提供getter setter等相应方法。


spring提供了BeanPostProcessor接口用于与bean类的的初始化等操作进行交互,
此接口提供的两种方法postProcessBeforeInitialization 及postProcessAfterInitialzation
作为与其在同一个beans中进行声明的bean类初始化前后的调用方法。
由于上述两个函数返回的是bean对象,故可以对bean进行修改。


有三种实施Spring Configuration MetaData解耦的方法,
XML 注释 java-based


对于XML中定义的bean的初始化情况,可以通过设定bean的scope属性来设定。
当scope取值为prototype时,每一次返回一个新的bean实例,
当scope取值为singleton时,每一次返回同一个bean实例。这也是默认时的属性值。


bean可以通过指定parent属性指定类似“基类”的类,这个“基类”
的一些属性可以被派生的bean继承与重写,但是这也仅仅是对于bean中
通过name value进行配置的部分可以这么做,对于其它属性及方法,是
不能实现类似于类继承的特性的,故可以说这是一种配置上的继承,而非类
结构上的。
由于仅仅是配置上的继承关系,故也可以定义“虚基类”,不必在工程中实际地
给出相应的类定义,而仅仅将class="*" 替换为abstract="*" 这样派生
bean通过parent属性即可通过id派生此abstract bean


tutorialspoint Learn Spring中关于依赖注入的方法主要指出了两种,一种
通过构造函数,另一种通过setter methods,
第一种通过构造函数的方法是符合已有的编程习惯的,即将依赖的部分作为
初始化参数传入。


第二种通过setter methods方法进行inner bean的设定的方法基本上就是将原始的对于
简单属性进行设定的bean方法的value取值从简单的仅能为字符串延伸为在
一个bean中定义另一个inner bean,这个inner bean可以代表这个bean的一个
一般的类成员,此类成员一般为自定义的(用于实现依赖注入的功能)。


上面介绍了将类实例作为bean属性的方法,即一般地通过inner bean,因为bean
一般作为与类相对应的层级是可以理解的。
讨论完对bean设定一般对象的类属性,那将容器作为bean对象的属性配置的需求
也就是可以理解的。
其方法就是将property原本用value描述的属性部分用内部树形结构进行描述,
这种处理与前面的inner bean是类似的,支持<map> <set> <list> <props>
最后一个props可以看成键值必须为String类型的Map.


对bean的property相应的value设定为null也是可以实现的,方法为将其内部
设定一个<null/>
如:
<bean id = "*" class = "*">
<property name = "*">
</null>
</property>
</bean>
当然地设定为空字符串更是简单。

下面给出一个bean的例子

package bean;/** * Created by admin on 2017/2/27. */public class Address {    private String line1;    private String line2;    private String city;    private String state;    private String zipCode;    private String country;    public Address(String line1, String line2, String city, String state, String zipCode, String country){        this.line1 = line1;        this.line2 = line2;        this.city = city;        this.state = state;        this.zipCode = zipCode;        this.country = country;    }    public String getLine1(){return line1;}    public void setLine1(String line1){this.line1 = line1;}    public String getLine2(){return line2;}    public void setLine2(String line2){this.line2 = line2;}    public String getCity(){return city;}    public void setCity(String city){this.city = city;}    public String getState(){return  state;}    public void setState(String state){this.state = state;}    public String getZipCode(){return zipCode;}    public void setZipCode(String zipCode){this.zipCode = zipCode;}    public String getCountry(){return country;}    public void setCountry(String country){this.country = country;}    @Override    public String toString(){        return line1 + "\n" + line2 + "\n" + city + "\n" + state + " " + zipCode + "\n" + country;    }}

package bean;/** * Created by admin on 2017/2/27. */public class Employee {    private String firstName;    private String lastName;    private Address homeAddress;    public Employee(){}    public Employee(String firstName, String lastName, Address homeAddress){        this.firstName = firstName;        this.lastName = lastName;        this.homeAddress = homeAddress;    }    public String getFirstName(){return firstName;}    public void setFirstName(String firstName){this.firstName = firstName;}    public String getLastName(){return lastName;}    public void setLastName(String lastName){this.lastName = lastName;}    public Address getHomeAddress(){return  homeAddress;}    public void setHomeAddress(Address homeAddress){this.homeAddress = homeAddress;}    @Override    public String toString(){        return firstName + " " + lastName + "\n" + homeAddress;    }}


package bean;/** * Created by admin on 2017/2/27. */import java.io.Serializable;public class Product implements Serializable {    private static final long serialVersionUID = 748392348L;    private String name;    private String description;    private float price;    public Product(){}    public Product(String name, String description, float price){        this.name = name;        this.description = description;        this.price = price;    }    public String getName(){return name;}    public void setName(String name){this.name = name;}    public String getDescription(){return description;}    public void setDescription(String description){this.description = description;}    public float getPrice(){return price;}    public void setPrice(float price){this.price = price;}}



/** * Created by admin on 2017/2/27. */import java.util.Calendar;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import bean.Employee;import bean.Product;public class Main {    public static void main(String [] args){        ApplicationContext context =  new ClassPathXmlApplicationContext(new String[]{"spring-config.xml"});        Product product1 = context.getBean("product", Product.class);        product1.setName("Excellent snake oil");        System.out.println("product1: " + product1.getName());        Product product2 = context.getBean("product", Product.class);        System.out.println("product2: " + product2.getName());        Product featuredProduct = context.getBean("featuredProduct", Product.class);        System.out.println(featuredProduct.getName() + ", " + featuredProduct.getDescription() + ", " + featuredProduct.getPrice());        Calendar calendar = context.getBean("calender", Calendar.class);        System.out.println(calendar.getTime());        Employee employee1 = context.getBean("employee1", Employee.class);        System.out.println(employee1.getFirstName() + " " + employee1.getLastName());        System.out.println(employee1.getHomeAddress());        Employee employee2 = context.getBean("employee2", Employee.class);        System.out.println(employee2.getFirstName() + " " + employee2.getLastName());        System.out.println(employee2.getHomeAddress());    }}

<?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 name = "product" class="bean.Product"/>        <bean name = "featuredProduct" class="bean.Product">            <constructor-arg name = "name" value="Ultimate Olive Oil"/>            <constructor-arg name = "description" value="The purest olive oil on the market"/>            <constructor-arg name = "price" value="9.95"/>        </bean>        <bean name = "featuredProduct2" class="bean.Product">            <constructor-arg index="0" value="Ultimate Olive Oil"/>            <constructor-arg index="1" value="The purest olive oil on the market"/>            <constructor-arg index="2" value="9.95"/>        </bean>        <bean id = "calender" class="java.util.Calendar" factory-method="getInstance"/>        <bean name = "employee1" class = "bean.Employee">            <property name = "homeAddress" ref = "simpleAddress" />            <property name = "firstName" value="Junior"/>            <property name = "lastName" value="Moore"/>        </bean>        <bean name = "employee2" class="bean.Employee">            <constructor-arg name = "firstName" value="Senior"/>            <constructor-arg name = "lastName" value="Moore"/>            <constructor-arg name="homeAddress" ref = "simpleAddress"/>        </bean>        <bean name = "simpleAddress" class="bean.Address">            <constructor-arg name = "line1" value="151 Corner Street"/>            <constructor-arg name = "line2" value=""/>            <constructor-arg name="city" value="Albany"/>            <constructor-arg name="state" value="NY"/>            <constructor-arg name = "zipCode" value="99999"/>            <constructor-arg name = "country" value="US"/>        </bean></beans>


 













0 0
原创粉丝点击