大数据学习+数据库知识

[JAVAEE] 实验03:Spring Bean的配置、实例化

2019-03-14  本文已影响1人  Topus

【一】实验目的:

(1)掌握Bean的实例化
(2)掌握Bean的装配方式
(3)掌握Bean的作用域和生命周期

【二】结构:

1配置(不具体介绍)
2实例化:构造方法实例化(最常用)、静态工厂实例化、实例工厂实例化
3作用域
4生命周期
5装配方式

【三】实验代码:

一、实例化

 BeanClass.java
package instance;
//一、bean的构造方法之 实例化(最常用)
public class BeanClass {    
    public String message;
    public BeanClass() {
        message = "构造方法实例化Bean";
    }
    public BeanClass(String s) {
        message = s;
    }
}
BeanInstanceFactory.java
package instance;
public class BeanInstanceFactory {
    public BeanClass createBeanClassInstance() {
        return new BeanClass("调用实例工厂方法实例化Bean");
    }
}

BeanStaticFactory.java

package instance;
//二、bean实例化之 静态工厂实例化
public class BeanStaticFactory {
    
    private static BeanClass beanInstance = new BeanClass("调用静态工厂方法实例化Bean");
    public static BeanClass createInstance() {
        return beanInstance;
    }
}

配置文件:ApplicationContext.xml

    <!-- 一、构造方法实例化Bean -->
    <bean id="constructorInstance" class="instance.BeanClass" scope="prototype"/>
    
    <!-- 二、静态工厂方法实例化Bean,createInstance为 静态工厂类BeanStaticFactory中的静态方法-->
    <bean id="staticFactoryInstance" class="instance.BeanStaticFactory"  factory-method="createInstance"/>
    
    <!-- 三、配置工厂 -->
    <bean id="myFactory" class="instance.BeanInstanceFactory"/>
    <!-- 还需要使用factory-bean属性指定配置工厂,应为这个是对象方法而不是类方法 ,使用factory-method属性指定使用工厂中哪个方法实例化Bean-->
    <bean id="instanceFactoryInstance" factory-bean="myFactory" factory-method="createBeanClassInstance"/>

测试:TestInstance.java

package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import instance.BeanClass;
public class TestInstance {
    public static void main(String[] args) {
        //初始化spring容器,通过路径加载配置文件
        @SuppressWarnings("resource")
        ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
        //一、构造方法的
        BeanClass b1 = (BeanClass)appCon.getBean("constructorInstance");
        System.out.println(b1 + "------" + b1.message);
        
        //二、静态工厂的
        BeanClass b2 = (BeanClass)appCon.getBean("staticFactoryInstance");
        System.out.println(b2+ "------" +b2.message);
        
        //三、实例工厂的
        BeanClass b3 = (BeanClass)appCon.getBean("instanceFactoryInstance");
        System.out.println(b3+ "------" +b3.message);
        
    }
}
实例化1 实例化2 实例化3

二、作用域(可作用的范围)

    <!-- 构造方法实例化Bean ,并设置为 prototype,默认为singleleton-->
    <bean id="constructorInstance" class="instance.BeanClass" scope="prototype"/>
作用域1

三、生命周期

配置文件:

    <!-- 3.1、配置bean的生命周期,使用init-method属性指定初始化方法,使用 destroy-method属性指定销毁方法-->
    <bean id="beanLife" class="life.BeanLife" init-method="initMyself" destroy-method="destroyMyself"/>


BeanLife.java
package life;
public class BeanLife {
    //相当于回调,以后可以写数据库的方法
    public void initMyself() {
        System.out.println(this.getClass().getName() + "ִ执行自定义的初始化方法");
    }
    public void destroyMyself() {
        System.out.println(this.getClass().getName() +"执行自定义的销毁方法");
    }
}
TestLife.java
package test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import life.BeanLife;
public class TestLife {
    public static void main(String[] args) {
        //初始化容器,加载配置文件
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println("获得对象前");
        BeanLife blife = (BeanLife)ctx.getBean("beanLife");
        
        System.out.println("获得对象后" + blife);
        
        ctx.close();//关闭容器
    }
}
生命周期1 生命周期2

四、装配方式(bean注入到容器的方式)

1.基于xml的装配方式

    <!-- 4.1.1 使用构造方法注入方式装配ComplexUser实例 user1-->
    <bean id="user1" class="assemble.ComplexUser">
        <constructor-arg index="0" value="chenheng1"/>
        <!--hobbyList-->
        <constructor-arg index="1">
            <list>
                <value>唱歌</value>
                <value>跳舞</value>
                <value>爬山</value>
            </list>
        </constructor-arg>
        <!--residenceMap  -->
        <constructor-arg index="2">
            <map>
                <entry key="dalian" value="大连"/>
                <entry key="beijing" value="北京"/>
                <entry key="shanghai" value="上海"/>
            </map>
        </constructor-arg>
        <!--aliasSet  -->
        <constructor-arg index="3">
            <set>
                <value>陈恒100</value>
                <value>陈恒101</value>
                <value>陈恒102</value>
            </set>
        </constructor-arg>
        <!--array  -->
        <constructor-arg index="4">
            <array>
                <value>aaaaa</value>
                <value>bbbbb</value>
            </array>
        </constructor-arg>
    </bean>
    
    
    <!--4.1.2 使用setter方法注入方式装配 ComplexUser实例user2 -->
    <bean id="user2" class="assemble.ComplexUser">
        <property name="uname" value="chenheng2"/>
        <property name="hobbyList">
            <list>
                <value>看书</value>
                <value>学习Spring</value>
            </list>
        </property>
        <property name="residenceMap">
            <map>
                <entry key="shenzhen" value="深圳"/>
                <entry key="gaungzhou" value="广州"/>
                <entry key="tianjin" value="天津"/>
            </map>
        </property>
        <property name="aliasSet">
            <set>
                <value>陈恒103</value>
                <value>陈恒104</value>
                <value>陈恒105</value>
            </set>
        </property>
        <property name="array">
            <array>
                <value>cccccc</value>
                <value>dddddd</value>
            </array>
        </property>
    </bean>
</beans>

ComplexUser.java

package assemble;
import java.util.List;
//4.1基于xml的装配方式

import java.util.Map;
import java.util.Set;
public class ComplexUser {
    
    private String uname;
    private List<String> hobbyList;
    private Map<String,String> residenceMap;
    private Set<String> aliasSet;
    private String[] array;
    /*
     * 使用构造方法注入,需要提供带参数的构造方法
     */
    public ComplexUser(String uname, List<String> hobbyList, Map<String, String> residenceMap, Set<String> aliasSet,
            String[] array) {
        super();
        this.uname = uname;
        this.hobbyList = hobbyList;
        this.residenceMap = residenceMap;
        this.aliasSet = aliasSet;
        this.array = array;
    }
    
    
    /*
     * 使用属性的setter方法注入,提供默认无参数的构造方法,并未住入的属性提供setter方法
     */
    public ComplexUser() {
        super();
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public void setHobbyList(List<String> hobbyList) {
        this.hobbyList = hobbyList;
    }
    public void setResidenceMap(Map<String, String> residenceMap) {
        this.residenceMap = residenceMap;
    }
    public void setAliasSet(Set<String> aliasSet) {
        this.aliasSet = aliasSet;
    }
    public void setArray(String[] array) {
        this.array = array;
    }
    @Override
    public String toString() {
        return "uname=" + uname + ";hobbyList =" + hobbyList + ";residenceMap=" 
    + residenceMap +";aliasSet=" + aliasSet + ";array=" + array;
    }
}

TestAssemble.java 测试

package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import assemble.ComplexUser;
public class TestAssemble {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
        //测试构造方法装配
        ComplexUser u1 = (ComplexUser)appCon.getBean("user1");
        System.out.println(u1);
        
        //测试setter方法注入
        ComplexUser u2 = (ComplexUser)appCon.getBean("user2");
        System.out.println(u2);
    }
}

2.基于注解的装配方式

@Component
该注解是一个泛化的概念,仅仅表示一个组件对象(Bean),可以作用在任何层次上

AnnotationUser.java
package annotation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component()//相当于@Component("annotationUser")或者@Component(value = "annotationUser"),annotationUser为Bean的id,默认为首字母小写的类名
public class AnnotationUser {
    @Value("chenheng")
    private String uname;
    
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    @Override
    public String toString() {
        return "uname=" + uname;
    }
}
在annotationContext里面告诉Spring在哪扫描
<?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.xsd">
    <!-- 使用context命名空间,通过Spring扫描指定包下所有Bean的实现类,进行注解解析 -->
    <context:component-scan base-package="annotation"/>
</beans>

在TestAnnotation里面测试(注意这里要导入spring-aop-5.0.5.RELEASE.jar的包)

package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import annotation.AnnotationUser;
public class TestAnnotation {
    public static void main(String[] args) {
        ApplicationContext appCon = new ClassPathXmlApplicationContext("annotationContext.xml");
        AnnotationUser au = (AnnotationUser)appCon.getBean("annotationUser");
        System.out.println(au.getUname());
    }
}

为了层次化:@Repository标注DAO层,@Service标注业务逻辑层、@Controller标注控制层
(1)创建dao层

package annotation.dao;
import org.springframework.stereotype.Repository;
@Repository("testDao")

public class TestDaoImpl implements TestDao{
    @Override
    public void save() {
        System.out.println("testDao save");
    }
}

(2)创建service层

package annotation.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import annotation.dao.TestDao;
@Service("testService")//�൱��@Service
public class TestSeviceImpl implements TestService{
    @Resource(name="testDao")
    
    private TestDao testDao;
    @Override
    public void save() {
        testDao.save();
        System.out.println("testService save");
    }
}

(3)创建Controller层

package annotation.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import annotation.service.TestService;
@Controller
public class TestController {
    @Autowired
    private TestService testService;
    public void save() {
        testService.save();
        System.out.println("testController save");
    }
}

配置注解:
之前已经配置过了(通过Spring扫描指定包下所有Bean的实现类)

<context:component-scan base-package="annotation"/>

创建测试类:

TestMoreAnnotation
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import annotation.controller.TestController;
public class TestMoreAnnotation {
    public static void main(String[] args) {
        ApplicationContext appCon = new ClassPathXmlApplicationContext("annotationContext.xml");
        TestController testcon = (TestController)appCon.getBean("testController"); 
        testcon.save();
    }
}
屏幕快照 2019-03-14 下午11.32.25.png
屏幕快照 2019-03-14 下午11.43.16.png

【四】遇到问题:

The import javax.servlet.annotation cannot be resolved

导入:servlet-api.jar包,然后在buildpath-addlibrary里面点击runtimesever添加服务器

上一篇下一篇

猜你喜欢

热点阅读