Study Notes _Spring_day01

Spring XML-based configuration

Jar package to copy the directory lib

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>

Create a file Bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--把对象的创建交给spring来管理-->
    <!--配置service-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
    <!--配置dao-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
</beans>

bean Tags: Let spring is used to configure the object is created and stored in the ioc container
id attribute: an object that uniquely identifies the
class attribute: Specifies the fully qualified class name of the object to be created

test

public class Client {
    //获取spring的Ioc核心容器并根据id获取对象
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取Bean对象
        IAccountService as = (IAccountService)ac.getBean("accountService");
        IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);
        System.out.println(as);
        System.out.println(adao);
    }

And the difference between BeanFactory ApplicationContext
BeanFactory Spring container is the top level interface.
ApplicationContext: It is when you create a core container, create a policy object is taken by way of immediate loading, that is, as long as one has finished reading the configuration file immediately create an object configuration file configured
to apply singleton object, often developed With this interface.
BeanFactory: It is when building core container, create an object strategy is by way of lazy loading, when acquiring the object id, and when you create the object. For many cases of applicable objects.

ApplicationContext three common implementation class:
ClassPathXmlApplicationContext: it can load the configuration file in the path, requires the configuration file must be in the path, or can not load (recommended).
FileSystemXmlApplicationContext: it can load the configuration file in the disk any path (must have access rights).
AnnotationConfigApplicationContext: It is used to read the annotation to create a container, the contents of tomorrow.
**

Bean label and manage objects details

bean label
for spring configuration objects allow to create, to call the default constructor with no arguments is class, no constructor with no arguments can not be created.
scope attribute:
action: acting range specified for the bean
values: and is commonly used in cases of a single embodiment
Singleton: Singleton (default)
the prototype: Example plurality of
request: the request scope is acting in web application
session: session scope to act on web application
global-session: the role of session-range cluster environment (global session scope), when not a clustered environment, it is the session
the init-method,: Specifies the class initialization method name
destroy-method: the specified class Disposal method name

Life Cycle bean object
singleton object
of Birth: When the container is created when the object is born
alive: as long as the container is still the object has been living
death: the destruction of container, objects demise
Summary: Singleton same life cycle and container objects
more cases of Object
Birth: When we use spring framework when the object is created for us
to live: as long as the objects have been alive during use.
Death: When the object is not a long time, and no other object reference by the Java garbage collected

Bean create objects in three ways

The first way : Create a default constructor.
The second way : use common in the plant to create objects (objects created using methods in a class, and into spring container)
instance of the class factory

 /**
  *模拟一个工厂类,该类可能存在于jar包中,无法通过修改源码的方式来提供默认构造函数
  * 
  */
 public class InstanceFactory {
     public IAccountService getAccountService() {
         return new AccountServiceImpl();
     }
 }

Configuration

<bean id = "instanceFactory" class = "com.itheima.factory.InstanceFactory"></bean>
     <bean id = "accountService"
      factory-bean="instanceFactory" factory-method="getAccountService"></bean>

This approach is: first create a plant to spring to manage, and then use the bean factory to call inside the method.
factory-bean: Examples of plants used to specify the bean id.
factory-method: Specifies the method creates an instance of an object factory.

The third way : to create an object using a static method in the plant (to create objects using a static method of a class, and into spring container)
static factory class

 public class StaticFactory {
     public  static IAccountService getAccountService() {
         return new AccountServiceImpl();
     }
 }

Configuration

<bean id = "accountService" class =
 "com.itheima.factory.StaticFactory" factory-method="getAccountService"></bean>

This method is to use a static method StaticFactory of getAccountService create objects, containers and stored in spring.
factory-method: static method specified production target.

Dependency Injection

The concept relies injection

Dependency injection (Dependency Injection) is the core of the concrete realization of spring ioc framework
by inversion of control, we create objects to create the spring, because the code is not possible to eliminate all depend on, such as:
business layer will still call the persistence layer method, and therefore it should be included in the business layer class implementation class object persistence layer. This is what we just wait frame by way of the configuration of the persistence layer objects can be passed in the business layer.

Method dependency injection

Injection using a constructor

Note that the assignment operation is not what we do, but by way of the configuration of the framework for us to make spring injection.
Account business layer implementation class

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("service中的saveAccount方法执行了。。。"+name+","+age+","+birthday);
    }
}

Profiles

<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>
<!-- 使用Date类的无参构造函数创建Date对象 -->
<bean id="now" class="java.util.Date"></bean>

Label involved: <constructor-arg>used to define the parameters of the constructor.

bean tag body personal understanding:

`<bean id="now" class="java.util.Date"></bean>
这个标签体的含义是读取class的全限定类名,
反射创建一个对象并且存入的核心容器中并使用,
比如我们可以用ref=“id”的这个方式把id里对应的对象取出来

Two injection methods using the set (used)

In class provides methods need to inject a set of members, create an object called only set method to assign attributes.

Account business layer implementation class

public class AccountServiceImpl2 implements IAccountService {
    private String name;
    private Integer age;
    private Date birthday;
    
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public void  saveAccount(){
        System.out.println(name+","+age+","+birthday);
    }
}

Profiles

  <!--set方法注入-->
    <bean id="accountService2" class="com.itheima.service.impl.AccountServiceImpl2">
        <property name="name" value="吕明辉"></property>
        <property name="age" value="20"></property>
        <property name="birthday" ref="now"></property>
    </bean>

Label involved: to define members to call the set method of its main attributes:

  • name: Get xxx part is a class of methods setXxx
  • value: String to basic data types and type of assignment
  • ref: Bean to other types of fields assigned value ref attribute should be configured as a profile id Bean

Injection set field

Field and its corresponding set of tag set according to the structure divided into two categories: the set of tags between the same structure can replace each other.

  1. Only key structure:

    An array of fields: tag represents a collection, the label of a member within the collection.
    List fields: tag represents a collection, the label of a member within the collection.
    The Set fields: tag represents the set, the label of a member in the set
    in which you can label each other ,, used interchangeably.

  2. The key to the structure:

    Map fields: 标签表示集合,标签表示集合内的键值对,其key属性表示键,value属性表示值.
    Properties字段: 标签表示集合,标签表示键值对,其key属性表示键,标签内的内容表示值.
    其中,标签之间,,标签之间可以互相替换使用.

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 void setMyStrs(String[] myStrs) {
        this.myStrs = myStrs;
    }

    public void setMyList(List<String> myList) {
        this.myList = myList;
    }

    public void setMySet(Set<String> mySet) {
        this.mySet = mySet;
    }

    public void setMyMap(Map<String, String> myMap) {
        this.myMap = myMap;
    }

    public void setMyprops(Properties myprops) {
        this.myprops = myprops;
    }

    public void  saveAccount(){
        System.out.println(Arrays.toString(myStrs));
        System.out.println(myList);
        System.out.println(myMap);
        System.out.println(mySet);
        System.out.println(myprops);
    }
}

<!--复杂/集合类型的注入-->
    <bean id="accountService3" class="com.itheima.service.impl.AccountServiceImpl3">
        <property name="myStrs">
            <array>
                <value>ss</value>
                <value>s1</value>
                <value>ss3</value>
            </array>
        </property>
        <property name="myList">
            <list>
                <value>ss</value>
                <value>s1</value>
                <value>ss3</value>
            </list>
        </property>
        <property name="mySet">
            <set>
                <value>ss</value>
                <value>s1</value>
                <value>ss3</value>
            </set>
        </property>
        <property name="myMap">
            <map>
              <entry key="a" value="21"></entry>
                <entry key="3a" value="221"></entry>
            </map>
        </property>
        <property name="myprops">
            <props>
                <prop key="asdasd">aaa</prop>
            </props>
        </property>
    </bean>
Published 33 original articles · won praise 0 · Views 503

Guess you like

Origin blog.csdn.net/naerjiajia207/article/details/103443184