当前位置: 移动技术网 > IT编程>软件设计>架构 > Spring基础——IOC九种bean声明方式

Spring基础——IOC九种bean声明方式

2019年12月10日  | 移动技术网IT编程  | 我要评论
Spring简介 Spring不是服务于开发web项目的功能,或业务。而是服务于项目的开发,方便各层间的解耦调用,方便对类的批量管理,是提高软件开发效率,降低后期维护成本的框架。 Spring的核心思想是IOC(控制反转),AOP(切面编程)两点。 IOC:即不再需要程序员去显式地`new`一个对象 ...

 

spring简介

spring不是服务于开发web项目的功能,或业务。而是服务于项目的开发,方便各层间的解耦调用,方便对类的批量管理,是提高软件开发效率,降低后期维护成本的框架。
spring的核心思想是ioc(控制反转),aop(切面编程)两点。
ioc:即不再需要程序员去显式地`new`一个对象,而是把spring框架把框架创建出的对象拿来用。因为是spring框架创建的对象,对象都在spring框架对象中保存,亦称为spring容器,这样spring就知道当前项目中都创建了哪些对象,这个对象归属于那一层,该如何管理。想使用spring的其他功能第一点就是要用spring的对象,也称为将控制权交给spring管理。
aop:对某种路径下的所有类,或有共同特性的类或方法统一管理,在原任务执行的前后,加入新功能。做出监控,初始化,整理,销毁等一系列统一的伴随动作。
如果你从事java编程有一段时间了, 那么你或许会发现(可能你也实际使用过) 很多框架通过强迫应用继承它们的类或实现它们的接口从而导致应用与框架绑死。这种侵入式的编程方式在早期版本的struts以及无数其他的java规范和框架中都能看到。spring竭力避免因自身的api而弄乱你的应用代码。spring不会强迫你实现spring规范的接口或继承spring规范的类,相反,在基于spring构建的应用中,它的类通常没有任何痕迹表明你使用了spring。 最坏的场景是, 一个类或许会使用spring注解, 但它依旧是pojo。
任何一个有实际意义的应用(肯定比hello world示例更复杂) 都会由两个或者更多的类组成, 这些类相互之间进行协作来完成特定的业务逻辑。 按照传统的做法, 每个对象负责管理与自己相互协作的对象(即它所依赖的对象) 的引用, 这将会导致高度耦合和难以测试的代码。

ioc声明bean

首先创建的maven poject,详细包结构如下

 其中aop会在下一篇进行讲解;

controller_.java

/**
     * @see httpservlet#doget(httpservletrequest request, httpservletresponse response)
     */
    protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
        // todo auto-generated method stub
        response.getwriter().append("served at: ").append(request.getcontextpath());
        classpathxmlapplicationcontext ctx=new classpathxmlapplicationcontext("/applicationcontext.xml"); 
        service_ s = (service_) ctx.getbean("service_impl1_new");
        system.out.println(s);
        s.show();
    }

由于spring无法单独演示,所以controller_.java是创建的是一个servlet,直接调用dopost或者doget方法,进行service的实现,输出service_对象s,执行show方法。

service_.java

public interface service_ {
    public void show();
}

创建一个service接口,用来实现spring。

1.无参构造方法声明bean

service_impl1.java

public class service_impl1 implements service_{

    
    public service_impl1() {
        // todo auto-generated constructor stub
        system.out.println("service1-无参构造方法");
    }
    @override
    public void show() {
        // todo auto-generated method stub
        system.out.println("service_impl1");
    }

}

重写service_的show方法输出实现了service_impl1,编写无参构造方法。

applicationcontext.xml

<!-- 默认构造方法 -->
    <bean id="service_impl1" class="com.zy.spring.service.serviceimpl.service_impl1"></bean>

只需要设置id与class,class对应service_impl1,id则是controller_.java调用的getbean中的参数。运行结果见自定义构造方法注入bean

2.自定义构造方法声明bean

service_impl2.java

public class service_impl2 implements service_{

    public service_impl2(int a) {
        // todo auto-generated constructor stub
        system.out.println("service2-自定义构造参数:"+a);
    }
    @override
    public void show() {
        // todo auto-generated method stub
        system.out.println("service_impl2");
    }

}

applicationcontext.xml

 <!-- 自定义构造方法 -->
     <bean id="service_impl2" class="com.zy.spring.service.serviceimpl.service_impl2">
         <constructor-arg index="0" value="1024"></constructor-arg>
     </bean>

<constructor-arg index="0" value="1024"></constructor-arg>这是构造方法中参数的设置,index顾名思义就是索引的意思,其中a参数是第0个,value是参数的值。

3.单实例 懒加载声明bean

service_impl3.java

public class service_impl3 implements service_{
    public service_impl3() {
        // todo auto-generated constructor stub
        system.out.println("service3-懒加载 单实例");
    }
    @override
    public void show() {
        // todo auto-generated method stub
        system.out.println("service_impl3");
    }

}

applicationcontext.xml

 <!--  单实例 懒加载 -->
    <bean id="service_impl3" class="com.zy.spring.service.serviceimpl.service_impl3" lazy-init="true" scope="singleton"></bean>

lazy-init="true" 设置懒加载,也就是调用的时候才会加载bean,不会自动加载;scope="singleton" 作用域标签,单实例也就是只创建一个实例。

4.参数引用声明bean

service_impl4.java

public class service_impl4 implements service_{
    
    service_ s3;
    
    
    public service_ gets3() {
        return s3;
    }
    public void sets3(service_ s3) {
        this.s3 = s3;
    }
    public service_impl4() {
        // todo auto-generated constructor stub
        system.out.println("service4-参数引用bean");
    }
    @override
    public void show() {
        // todo auto-generated method stub
        system.out.println("service_impl4");
    }

}

applicationcontext.xml

<!-- 参数引用bean -->
    <bean id="service_impl4" class="com.zy.spring.service.serviceimpl.service_impl4">
       <property name="s3" ref="service_impl3"></property>
    </bean>

<property name="s3" ref="service_impl3"></property> 参数标签,name是service_impl4中的参数s3,ref链接要引用的bean。

5.初始化属性声明bean

service_impl5.java

public class service_impl5 implements service_{
    string name;
    arraylist<string> list;
    hashmap<string, string> map;
    hashset<integer> set;
    
    
    @override
    public int hashcode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((list == null) ? 0 : list.hashcode());
        result = prime * result + ((map == null) ? 0 : map.hashcode());
        result = prime * result + ((name == null) ? 0 : name.hashcode());
        result = prime * result + ((set == null) ? 0 : set.hashcode());
        return result;
    }
    @override
    public boolean equals(object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getclass() != obj.getclass())
            return false;
        service_impl5 other = (service_impl5) obj;
        if (list == null) {
            if (other.list != null)
                return false;
        } else if (!list.equals(other.list))
            return false;
        if (map == null) {
            if (other.map != null)
                return false;
        } else if (!map.equals(other.map))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (set == null) {
            if (other.set != null)
                return false;
        } else if (!set.equals(other.set))
            return false;
        return true;
    }
    @override
    public string tostring() {
        return "service_impl5 [name=" + name + ", list=" + list + ", map=" + map + ", set=" + set + "]";
    }
    public string getname() {
        return name;
    }
    public void setname(string name) {
        this.name = name;
    }
    public arraylist<string> getlist() {
        return list;
    }
    public void setlist(arraylist<string> list) {
        this.list = list;
    }
    public hashmap<string, string> getmap() {
        return map;
    }
    public void setmap(hashmap<string, string> map) {
        this.map = map;
    }
    public hashset<integer> getset() {
        return set;
    }
    public void setset(hashset<integer> set) {
        this.set = set;
    }
    
    
    
    public service_impl5() {
        // todo auto-generated constructor stub
        system.out.println("service5-初始化属性");
    }
    @override
    public void show() {
        // todo auto-generated method stub
        system.out.println("service_impl5");
    }

}

其中初始化参数有list,map,set以及普通参数,重写了hashcode和equals方法,详见hashmap内存泄漏;重写tostring方法用来输出初始化属性。

applicationcontext.xml

<!--     初始化属性  -->
     <bean id="service_impl5" class="com.zy.spring.service.serviceimpl.service_impl5">
         <property name="name" value="zy"></property>
         <property name="map">
             <map>
                 <entry key="aaa" value="aaa"></entry>
                 <entry key="bbb" value="bbb"></entry>
             </map>
         </property>
         
         <property name="list">
             <list>
                 <value type="java.lang.string">qqq</value>
                 <value type="java.lang.string">www</value>
             </list>
         </property>
         
         <property name="set">
             <set>
                 <value type="java.lang.integer">111</value>
                 <value type="java.lang.integer">222</value>
             </set>
         </property>
     </bean>

其中map标签内使用<entry key="aaa" value="aaa"></entry>进行赋值。其他的正常使用property和value进行赋值。

6.初始化属性引用方法返回值声明bean

service_impl6.java

public class service_impl6 implements service_{
    string s5_tostring;
    
    
    
    public string gets5_tostring() {
        return s5_tostring;
    }
    public void sets5_tostring(string s5_tostring) {
        this.s5_tostring = s5_tostring;
    }
    
    public service_impl6() {
        // todo auto-generated constructor stub
        system.out.println("service6-调用方法返回值");
    }
    @override
    public void show() {
        // todo auto-generated method stub
        system.out.println("service_impl6 返回值"+s5_tostring);
    }

}

其中调用了service_impl5的tostring方法并且进行了输出。

applicationcontext.xml

<!--     调用方法返回值 -->
      <bean id="service_impl6" class="com.zy.spring.service.serviceimpl.service_impl6">
            <property name="s5_tostring">
                <bean class="org.springframework.beans.factory.config.methodinvokingfactorybean">
                    <property name="targetobject" ref="service_impl5"></property>
                    <property name="targetmethod" value="tostring"></property>
                </bean>
            </property>
      </bean>

<bean class="org.springframework.beans.factory.config.methodinvokingfactorybean">固定用来声明调用方法返回值。

targetobject——目标的bean

targetmethod——目标的方法

7.静态工厂——声明工厂bean

service_impl7.java

public class service_impl7 implements service_{
    
    public static service_ staticfactory(int num) {
        switch (num) {
        case 1:
            return new service_impl1();
        case 2:
            return new service_impl2(100);
        case 3:
            return new service_impl3();
        case 4:
            return new service_impl4();
        case 5:
            return new service_impl5();
        default:
            return new service_impl6();
        }
    }
    
    public service_impl7() {
        // todo auto-generated constructor stub
        system.out.println("service7-静态工厂");
    }
    @override
    public void show() {
        // todo auto-generated method stub
        system.out.println("service_impl7");
    }

}

工厂在实现类中使用了switch语句进行模拟,静态工厂在方法前加上static关键字,分别调用上面的其他实现类方法。

applicationcontext.xml

<!--   静态工厂 -->
       <bean id="service_impl7" class="com.zy.spring.service.serviceimpl.service_impl7" factory-method="staticfactory" >
               <constructor-arg name="num" value="2"></constructor-arg>
       </bean>

使用构造方法注入的方法来赋值<constructor-arg name="num" value="2"></constructor-arg> ;factory-method="staticfactory" ( factory-method工厂的方法名)

8.实例工厂——声明工厂bean

service_impl8.java

public class service_impl8 implements service_{
    
    public  service_ factory1(int num) {
        switch (num) {
        case 1:
            return new service_impl1();
        case 2:
            return new service_impl2(100);
        case 3:
            return new service_impl3();
        case 4:
            return new service_impl4();
        case 5:
            return new service_impl5();
        default:
            return new service_impl6();
        }
    }
    
    public service_impl8() {
        // todo auto-generated constructor stub
        system.out.println("service8-实例工厂");
    }
    @override
    public void show() {
        // todo auto-generated method stub
        system.out.println("service_impl8");
    }

}

applicationcontext.xml

  <!-- 实例工厂 -->
      <bean id="service_impl8" class="com.zy.spring.service.serviceimpl.service_impl8"  >
       </bean>
    <bean id="service_impl8_new"  factory-bean="service_impl8" factory-method="factory1">
        <constructor-arg name="num" value="2"></constructor-arg>
    </bean>

创建实例工厂bean,首先创建一个实例工厂的bean,然后再创建一个工厂方法的bean去调用工厂的bean。

调用的时候要调用工厂方法的bean,这里就要调用service_impl8_new

9.注解声明bean

@service:用于标注业务层组件
@controller:用于标注控制层组件(如struts中的action)
@repository:用于标注数据访问组件,即dao组件
@component(value="*"):泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注

service_impl9.java

@service
public class service_impl9 implements service_{

    
    public service_impl9() {
        // todo auto-generated constructor stub
        system.out.println("service9-注解注入bean");
    }
    @override
    public void show() {
        // todo auto-generated method stub
        system.out.println("service_impl9");
    }

}

@service进行bean的声明(注解只能声明无参构造方法),使用注解默认声明的bean是类名的首字母小写,这里声明的bean的id应该是service_impl9。

applicationcontext.xml

 <!-- 注解扫描ioc根目录 -->
        <context:component-scan base-package="com.zy.spring"> 
     <context:exclude-filter type="annotation" expression="org.springframework.stereotype.controller"/><!-- 扫描不包括controller -->
    </context:component-scan>

使用注解需要加上注解扫描,其中base-package是扫描的目录,一般使用的是项目的根目录,以后使用springmvc的话,就不用扫描controller。

 注解写入bean

@resource(name="*" type="*")bean写入
@autowired/@qualifier
@inject/@named

 

 

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网