Spring Framework Learning (2) Spring Bean model assembly

Foreword

Record learning experience, before the next first step
relies Spring core mechanism of injection, change the traditional programming practice, referred to the completion of the Spring container, into the application when required to instantiate the component, which will depend on the relationship between the decoupling components the key in the xml configuration file with the bean element

ApplicationContext

Spring IoC container Bean is the core design, using Java BeanFactory factory model, to achieve the creation of JavaBean JavaBean defined by reading from a xml configuration file, configuration and management
ApplicationContext extends BeanFactory container, inheritance BeanFactory interface, ApplicationContext interface has three common implementation class
(1) ClassPathXmlApplicationContext
Looking xml configuration file from the address ClassPath class, find and load the working examples of the ApplicationContext

 ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml ");

(2) FileSystemXmlApplicationContext
looking from a specified file system path specified in the xml configuration file, to locate and mount the work ApplicationContext instantiation of
classes directory:

ApplicationContext ctx=new FileSystemXmlApplicationContext("classpath:applicationContext.xml")

relative path

 ApplicationContext ctx=new FileSystemXmlApplicationContext("src\\applicationContext.xml");

Absolute path

ApplicationContext ctx=new FileSystemXmlApplicationContext("C:\\TomCat\\apache-tomcat-9.0.22\\webapps\\sy8\\src\\applicationContext.xml");

ClassPathXmlApplicationContext difference between the read configuration file in the specified configuration file with parameter FileSystemXmlApplicationContext position, access to resources outside classpath

(3) XmlWebApplicationContext
Looking from a Web application specified in the xml configuration file to find examples of the work and the completion of loading the ApplicationContext
Web project
through the above three categories manually instantiated ApplicationContext container, but for the Web project not in the Java programs, Web items start is the responsibility of the appropriate Web server, instances of work in Web projects ApplicationContext container is best left to complete the Web server, Spring provides two methods:
(1) based on contextLoaderListener achieved (and more applicable to Servlet2.4 )
in xml:

<!--指定Spring配置文件的位置,多个配置文件以逗号分隔-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!--指定以listener方式启动Spring容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

(2) based on ContextLoaderServlet implemented
in web.xml:

  <!--指定Spring配置文件的位置,多个配置文件以逗号分隔-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!--以servlet方式启动Spring容器-->
    <servlet>
        <servlet-name>context</servlet-name>
        <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
    </servlet>

Bean scopes

The most important task is to create and manage JavaBean container life cycle
Bean scope is the living space Bean instance or effective range of
Spring defines five scoped Bean instance to meet the different circumstances

  • singleton (single instance scope): each Spring IoC container, a bean definition object instance corresponds to a
  • the prototype (prototype scope mode): a bean definition object instances corresponding to a plurality of
  • request: in a http request, the container will return the same instance of the Bean and the http session for different requests, it will return different instances
  • session: In a http session, the vessel will return to the same instance of Bean, for different http session request returns a different instance
  • global session: in a global http session, the vessel will return the same instance of the Bean

request, session, global session only used in Web-based applications
when a user uses the Spring WebApplicationContext, can request, session, global session
(. 1) Singleton
Spring bean instances the IoC container will present a shared
applicationContext.xml

<bean id="helloworld" class="com.HelloWorld" scope="singleton">
        <property name="userName" value="zhangsan"></property>
    </bean>

Test category

package com.show;

import com.HelloWorld;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestHelloWorld {
    public static void main(String [] args){
        //加载xml配置
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        //获得配置中的实例
        HelloWorld helloWorld=(HelloWorld)ctx.getBean("helloworld");
        HelloWorld helloWorld1=(HelloWorld)ctx.getBean("helloworld");
        System.out.println(helloWorld==helloWorld1);
        //调用方法
        helloWorld.show();
    }
}

Here Insert Picture Description
(2) prototype
each time create a new request for the bean bean instance
the above xml prototype in scope to

<bean id="helloworld" class="com.HelloWorld" scope="prototype">
        <property name="userName" value="zhangsan"></property>
    </bean>

Test results class:
Here Insert Picture Description

Bean assembly based Annotation (annotation) of

When too many applications Bean, xml configuration bloated, jdk5 began offering Annotation annotation features
Annotation Spring-defined annotations

  1. @ Component annotation
    concept of generalization and represents a component (Bean), may act at any level
  2. @Repository annotation
    class identifying a data access layer (DAO layer) of Spring Bean
  3. @Service notes
    for the business layer, is currently working with the same function @Component
  4. @Controller
    identification layer components, and the current function the same as Component

Use @ Component, @ Repository, @ Service, @ Controller annotation, Spring will automatically create a corresponding BeanDefinition object and register to an ApplicationContext, these classes has become a Spring managed components

  1. @Autowired annotation
    for the Bean properties variables, methods and constructors SET attribute to mark, with the corresponding annotation processor automatically configured into a work Bean
  2. @Resource annotation
    corresponds @Autowired, configuring a corresponding annotation processor completes autoconfiguration Bean work, the difference in types of assembled @Autowired Bean default installation, equipped as the default @Resource Bean instance name, @ Resource including name, type two important attribute, Spring resolve the name attribute to the name of Bean instance, the type of resolve to Bean instance type
  3. @Qualifier annotation
    and @Autowired annotation with the default parameters specified by the assembled Bean type is changed to be assembled by Bean instance name, Bean annotated by the name of the instance of @Qualifier

Examples appreciated (Step login system)
(1) modify the implementation of the interface class UserDaoImpl UserDao
use @Repository annotation, the data access layer class UserDaoImpl identification of the Spring Bean, Bean by identifying the name of the attribute value userDao

import com.Dao.UserDao;
import org.springframework.stereotype.Repository;

@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Override
    public boolean login(String loginName, String loginPwd) {
        if (loginName.equals("admin")&&loginPwd.equals("123456")){
            return true;
        }
        else return false;
    }
}

(2) modify the implementation class UserServiceImpl UserService interface
@Service annotation identifies business logic class UserServiceImpl Spring Bean, entitled that userService
Bean used @Autowired annotations UserDAO userDAO type attribute, the name of the instance of the container is a step 1Spring userDao fitted into the Bean properties userDao

package com.Dao.Impl;

import com.Dao.Service.UserService;
import com.Dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    public void setUserDao(UserDao userDao){
        this.userDao=userDao;
    }

    @Override
    public boolean login(String loginName, String loginPwd) {
       return userDao.login(loginName,loginPwd);
    }
}

(3) modify the xml configuration file
xml file bean element no need to start the automatic scan function Bean configuration file in the Spring, Spring container will scan all the class of this group and its sub-package package

<?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:component-scan base-package="com"></context:component-scan>

   
</beans>

(4) run the test program TestLogin
Here Insert Picture Description

Notes the xml configuration file is no longer bloated, so that the "zero-configuration" forward

Released eight original articles · won praise 0 · Views 166

Guess you like

Origin blog.csdn.net/key_768/article/details/103934104