当前位置: 移动技术网 > IT编程>开发语言>Java > Spring笔记2

Spring笔记2

2019年07月19日  | 移动技术网IT编程  | 我要评论

spring中bean的细节之作用范围**

 <!--<bean的作用范围
        bean标签的scope属性:
            作用;用于指定bean的作用范围
            取值:
                singleton:单例的(默认值)
                prototype:多例的
                request:作用于web应用的请求范围
                session:作用于web应用的会话范围
                global-session:作用于集群环境的会话范围(全局会话范围),当不是集群环境时,他是session
    -->
    <bean id="accountservice" class="com.itheima.factory.staticfactory" factory-method="getaccountservice" scope="prototype"></bean>

bean对象的生命周期

单例对象:

出生:当容器创建是对象出生

活着:只要容器还在,对象一直活着

死亡:容器销毁,对象消亡

多例对象:

出生:当我们使用对象时spring框架为我们创建

活着:对象只要是在使用过程中就一直活着

死亡:当对象长时间不用,且没有别的对象引用是,由java的垃圾回收器回收

spring的依赖注入

<!--spring中的依赖注入-->
        <!--依赖注入:-->
            <!--dependenccy injection-->
        <!--ioc的作用:-->
            <!--降低程序间的耦合(依赖关系)-->
        <!--依赖关系的管理:-->
            <!--以后都交给spring来维护-->
        <!--在当前类需要用到其他类对象,由spring为我们提供,我们只需在配置文件中说明-->
        <!--依赖关系的维护:-->
            <!--就称为依赖注入-->
        <!--依赖注入:-->
            <!--能注入的数据:有三类-->
                <!--基本类型和string-->
                <!--其他bean类型(在配置文件或者注解配置过的bean)-->
                <!--复杂类型/集合类型-->
            <!--注入的方式:-->
                <!--第一种:使用构造函数提供-->
                <!--第二种:使用set方法提供-->
                <!--第三种:使用注解提供-->

1.构造函数注入

首先定义可注入的变量

public class accountserviceimpl implements iaccountservice {
    private string name;
    private integer age;
    private date birthday;
    public accountserviceimpl(string name,integer age,date birthday){
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }
    public void  saveaccount(){
        system.out.println(name+":"+age+":"+birthday);
    }
}
<!--构造函数注入
        使用标签:constructor-arg
        标签中的属性:
            type:用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型
            index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值,索引的位置从0开始
            name:用于指定给构造函数中指定名称的参数赋值(常用)
        =======================================
        以上三个用于指定给构造函数的哪个参数赋值
        =======================================
            value:用于提供基本类型和string类型的数据
            ref:用于指定其他的bean类型,他指的就是spring的ioc核心容器中出现过的bean对象
    -->
    <bean id="accountservice" class="com.itheima.service.impl.accountserviceimpl">
        <constructor-arg name="name" value="迪丽热巴"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
    </bean>
    <!--配置日期对象-->
    <bean id="now" class="java.util.date"></bean>

img

创建测试类调用对象方法,查看注入是否成功

public class client {

    public static void main(string[] args) {
        //获取核心容器对象
        applicationcontext ac = new classpathxmlapplicationcontext("bean.xml");
        //2.根据id(唯一标识)获取bean对象
        iaccountservice as = (iaccountservice)ac.getbean("accountservice");
        system.out.println(as);
    }
}

img

set方法注入:

1.给属性提供set,get方法

package com.itheima.service.impl;

import com.itheima.service.iaccountservice;

import java.util.date;

/**
 * 账户的业务层实现类
 */
public class accountserviceimpl2 implements iaccountservice {
    private string name;
    private integer age;
    private date birthday;

    public string getname() {
        return name;
    }

    public void setname(string name) {
        this.name = name;
    }

    public integer getage() {
        return age;
    }

    public void setage(integer age) {
        this.age = age;
    }

    public date getbirthday() {
        return birthday;
    }

    public void setbirthday(date birthday) {
        this.birthday = birthday;
    }

    public void  saveaccount(){
        system.out.println(name+":"+age+":"+birthday);
    }
}

2.xml配置

<bean id="now" class="java.util.date"></bean>
        <!--set方法注入
            涉及的标签:property
            标签的属性
                name:用于指定注入时所调用的set方法名称
                value:用于提供基本类型和string类型的数据
                ref:用于指定其他的bean类型,他指的就是spring的ioc核心容器中出现过的bean对象
        -->
    <bean id="accountservice2" class="com.itheima.service.impl.accountserviceimpl2">
        <property name="name" value="迪丽热巴2"></property>
        <property name="age" value="19"></property>
        <property name="birthday" ref="now"></property>
    </bean>

3.测试类

package com.itheima.ui;


import com.itheima.service.iaccountservice;

import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;

/**
 * 模拟一个表现层,用于调用业务层
 */
public class client {

    public static void main(string[] args) {
        //获取核心容器对象
        applicationcontext ac = new classpathxmlapplicationcontext("bean.xml");
        //2.根据id(唯一标识)获取bean对象
        iaccountservice as = (iaccountservice)ac.getbean("accountservice2");
       as.saveaccount();
    }
}

img

注入结合数据

1.类中添加集合属性

package com.itheima.service.impl;

import com.itheima.service.iaccountservice;

import java.util.*;

/**
 * 账户的业务层实现类
 */
public class accountserviceimpl3 implements iaccountservice {
    private string[] mystrs;
    private list<string> mylist;
    private set<string> myset;
    private map<string,string> mymap;
    private properties myprops;

    public string[] getmystrs() {
        return mystrs;
    }

    public void setmystrs(string[] mystrs) {
        this.mystrs = mystrs;
    }

    public list<string> getmylist() {
        return mylist;
    }

    public void setmylist(list<string> mylist) {
        this.mylist = mylist;
    }

    public set<string> getmyset() {
        return myset;
    }

    public void setmyset(set<string> myset) {
        this.myset = myset;
    }

    public map<string, string> getmymap() {
        return mymap;
    }

    public void setmymap(map<string, string> mymap) {
        this.mymap = mymap;
    }

    public properties getmyprops() {
        return myprops;
    }

    public void setmyprops(properties myprops) {
        this.myprops = myprops;
    }

    public void saveaccount() {
        system.out.println(arrays.tostring(mystrs));
        system.out.println(mylist);
        system.out.println(myset);
        system.out.println(mymap);
        system.out.println(myprops);
    }
}

3.配置xml

数组中的元素使用value标签提供

 <!--复杂类型的注入/集合类型的注入
        用于给list结构集合注入的标签
            list array set
        用于给map结构集合注入的标签有
            map props
        结构相同,标签可以互换
    -->
    <bean id="accountservice3" class="com.itheima.service.impl.accountserviceimpl3">
        <property name="mystrs">
        <array>
            <value>李白</value>
            <value>苏轼</value>
            <value>辛弃疾</value>
        </array>
    </property>

        <property name="mylist">
            <list>
                <value>李白</value>
                <value>苏轼</value>
                <value>辛弃疾</value>
            </list>
        </property>

        <property name="myset">
            <set>
                <value>李白</value>
                <value>苏轼</value>
                <value>辛弃疾</value>
            </set>
        </property>
<!--===============上面三个是单列集合=====================-->

        <property name="mymap">
            <map>
                <entry key="李白" value="李清照"></entry>
                <entry key="苏轼" value="苏东坡"></entry>
                <entry key="迪丽热巴" value="古娜力扎"></entry>
            </map>
        </property>

        <property name="myprops">
            <props>
                <prop key="古娜力扎">迪丽热巴</prop>
                <prop key="佟丽娅">贾静雯</prop>
            </props>
        </property>
    </bean>

4.测试数据是否注入集合

package com.itheima.ui;


        import com.itheima.service.iaccountservice;

        import org.springframework.context.applicationcontext;
        import org.springframework.context.support.classpathxmlapplicationcontext;

/**
 * 模拟一个表现层,用于调用业务层
 */
public class client {

    public static void main(string[] args) {
        //获取核心容器对象
        applicationcontext ac = new classpathxmlapplicationcontext("bean.xml");
        //2.根据id(唯一标识)获取bean对象
        iaccountservice as = (iaccountservice)ac.getbean("accountservice3");
        as.saveaccount();
    }
}

img

使用注解创建对象

1.配置xml,告知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">
<!--告知spring在创建容器是要扫描的包,配置所需要的标签在context名称空间和约束中-->
        <context:component-scan base-package="com.itheima"></context:component-scan>
</beans>

2.加上注解:@component

@component
//作用:用于把当前类对象存入spring容器中
//属性 value:用于指定bean的id,当我们不写是,他的默认是当前类名,且首字母该小写
public class accountserviceimpl implements iaccountservice {
    private iaccountdao accountdao = new accountdaoimpl();
    public accountserviceimpl(){
        system.out.println("对象创建了");
    }
    public void  saveaccount(){ accountdao.saveaccount();
    }
}

由component衍生的注解

controller:一般用于表现层

service:一般用在业务层

repository:一般用在持久层

以上三个注解他们的作用和属性与component是一模一样的,他们三个是spring框架为我们提供明确三层使用的注解,使我们的三层对象更加清晰

自动按照类型注入

autowired注解:作用:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功

出现位置:可以是变量上,也可以是方法上

细节:在使用注解注入时,set方法就不是必须的

qualifier注解:作用:在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用。但是在给方法参数注入时可以

属性value:用于指定注入bean的id。

resource注解:作用:直接按照bean的id注入。它可以独立使用

属性name:用于指定bean的id。

以上三个注入都只能注入其他bean类型的数据,而基本类型和string类型无法使用上述注解实。另外,集合类型的注入只能通过xml来实现。

value注解:作用用于注入基本类型和string类型的数据;

属性value:用于指定数据的值

spring的新配置(取出xml的配置文件)

现在需要使用注解来去除 通过配置xml来获取的两个bean对象

 <!--配置queryrunner-->
    <bean id="runner" class="org.apache.commons.dbutils.queryrunner" scope="prototype">
        <constructor-arg name="ds" ref="datasource"></constructor-arg>
    </bean>

    <bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource">
        <property name="driverclass" value="com.mysql.jdbc.driver"></property>
        <property name="jdbcurl" value="jdbc:mysql:///eesy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="12345"></property>
    </bean>

实现方式

//configuration 作用,指定当前类是一个配置类
//componentscan 作用,用于通过注解指定spring在创建容器是要扫描的包
//

@configuration
@componentscan(basepackages = "com.itheima")//指定创建容器是要扫描的包
public class springconfiguration {
    //用于创建一个queryrunner对象
    @bean(name="runner")//用于把当前方法的返回值作为bean对象存入spring的ioc容器中
    public queryrunner createqueryrunner(datasource datasource){
        return new queryrunner(datasource);
    }
    // 创建数据源对象
    @bean(name="datasource")
    public datasource createdatasource(){
        combopooleddatasource ds = new combopooleddatasource();
        try {
            ds.setdriverclass("com.mysql.jdbc.driver");
        } catch (propertyvetoexception e) {
            e.printstacktrace();
        }
        ds.setjdbcurl("jdbc:mysql:///eesy");
        ds.setuser("root");
        ds.setpassword("12345");
        return ds;
    }
}

在使用xml配置是获取容器是通过如下

applicationcontext ac = new classpathxmlapplicationcontext("bean.xml");

那么我们现在通过注解来获取容器就应该使用另外一个类来获取,如下

 applicationcontext ac = new annotationconfigapplicationcontext(springconfiguration.class);

运行案例是报了错误:

nosuchbeandefinitionexception: no qualifying bean of typeavailable: expected at least 1 bean which qualifies as autowire candidate. dependency annotations:

具体错误信息如下

img

关键字:nosuchbeandefinitionexception,说没有bean对象

原来是忘记在bean对象前加注解了dao层,和service层都要加

img

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网