Spring basis --IOC nine kinds of bean declaratively

 

Spring Profile

Spring does not serve the function of web development project, or business. But to serve the development of the project, calling convenience decoupling between the layers, convenient batch class management, is to improve software development efficiency and reduce costs of post-maintenance framework.
Spring is the core idea IOC (Inversion of Control), AOP (section Programming) two points.
IOC: ie, no longer requires the programmer to explicitly `new` an object, but the Spring Framework to create a framework with objects brought. Because it is the object spring framework created objects are stored in a spring frame object, also known as spring container, so spring will know that the current project will create what object that belongs to that layer, how to manage. Want to use the other functions of the first spring point is to use the spring of objects, also known as management control to the spring.
AOP: for all classes under certain path, or class or method common characteristics of unified management, before and after the execution of the original task, adding new features. Make monitoring, initialization, sorting, destruction and a series of accompanying unified action.
If you work in the Java programming for some time, you may find (you may also actually used) framework inherited a lot of their class or implement their interfaces with leading application framework tied down by forcing the application. This invasive way of programming in earlier versions of Struts and countless other Java specifications and frameworks can see. Spring trying to avoid its own API and mess up your application code. Spring does not force you to realize Spring interfaces or extend Spring specification standard class, on the contrary, in the Spring-based applications built in, it's like you usually do not show any signs of use Spring. The worst scenario is that a class might use Spring annotations, but it is still a POJO.
Application of any meaningful (certainly more complex than Hello World example) will be composed of two or more classes, mutual collaboration between these classes to complete the specific business logic. According to the traditional approach, each object with the object itself is responsible for managing mutual cooperation (ie, it depends on the object) reference, which will lead to code highly coupled and difficult to test.

IOC statement Bean

Maven Poject first create detailed packet structure is as follows

 AOP which will be the next one to explain;

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();
    }

As Spring alone can not demonstrate, so Controller_.java is created is a Servlet, direct call doPost or doGet method, to implement Service, the output target Service_ s, execute the show method.

Service_.java

public interface Service_ {
    public void show();
}

Creating a Service interface, used to implement Spring.

1. Statement bean constructor with no arguments

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_ rewrite the show method to achieve the outputs Service_Impl1, write constructor with no arguments.

ApplicationContext.xml

<! - default constructor -> 
    <the bean ID = "service_Impl1" class = "com.zy.spring.service.serviceimpl.Service_Impl1"> </ the bean>

Id only need to set the class, class corresponding to Service_Impl1, id is getBean Controller_.java call parameters. Run results are custom Constructor injection bean

2. Customize the constructor statement 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> which is provided constructor parameter, index name suggests is the index means, wherein a parameter of 0, value is the value of the parameter .

3. Single Instance lazily statement 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

 

 

Guess you like

Origin www.cnblogs.com/zhangyuan1024/p/12009141.html