SSM-Spring(1)

Spring

  • Spring is an open source free framework
  • Spring is a lightweight, non-invasive framework
  • Inversion of Control (IOC), Aspect Oriented Programming (AOP)
  • Support transaction processing, support for framework integration

IOC theory

  1. UserDao
  2. UserDaoImp
  3. UserSevice
  4. UserServiceImp

In the past, user needs may affect the original code.
Use a set.

public void setUserDao(UserDao userDao){
    
    
    this.userDao = userDao;
}
  • Before, the object was actively created, and the control was in the hands of the programmer.
  • After using set, the object is passively accepted.

Inversion of Control (IoC) is a design idea, DI (Dependency Injection) is a way to implement IoC, and some people think that Di is just another term for IoC. In programs without IoC, we use object-oriented programming. The creation of objects and their dependencies are completely hard-coded in the program. The creation of objects is controlled by the program itself. After the inversion of control, the creation of objects is transferred to a third party. I think The so-called inversion of control is: the way to obtain dependent objects is reversed.
When configuring the Bean in xml mode, the definition information of the Bean is separated from the implementation, and the two can be combined into one by the way of annotation. The definition information of the Bean is directly defined in the implementation class in the form of annotations, thus achieving The purpose of zero configuration
Inversion of control is a way to produce or obtain a specific object through a description (XML or annotation) and through a third party. It is the IoC container that implements the inversion of control in Spring, and its implementation method is Dependency Injection (DI)

Set up Spring environment

in pojo

package com.kuang.dao;

public class Hello {
    
    
    private String str;
    public String getName(){
    
    
        return str;
    }
    public void setName(String name){
    
    
        this.str = name;
    }
    public void show(){
    
    
        System.out.println("Hello" + str);
    }
}

resource

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--bean = 对象-->
    <!--id = 变量名-->
    <!--class = new的对象-->
    <!--property 相当于给对象中的属性设值-->
    
    <bean id="hello" class="com.hou.pojo.Hello">
        <property name="name" value="Spring"/>
    </bean>
</beans>

test

public class Mytest  {
    
    
    public static void main(String[] args) {
    
    
        //获取Spring的上下文对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象现在都在Spring中的管理
        Hello hello = (Hello)context.getBean("hello");
        System.out.println(hello.toString());
    }
}

Who created the Hello object?

The hello object is created by Spring

How are the properties of the Hello object set?

The properties of the hello object are set by the Spring container,

This process is called inversion of control:

Control: Who controls the creation of objects, traditional application objects are created under the control of the program itself, after using Spring, the objects are created by Spring.

Reverse: The program itself does not create an object, but becomes a passive receiving object.

Dependency injection: It uses the set method to inject.

IOC is a programming idea, from active programming to passive reception.

You can browse the underlying source code through newClassPathXmlApplicationContext.

OK, up to now, we don't need to change the program at all. To achieve different operations, we only need to modify the xml configuration file, the so-called IoC, in one sentence: the object is created, managed, and assembled by Spring!

Note that
all Beans have been instantiated by Spring as soon as they are registered, and different objects of the same type instance in Spring actually point to the same object.

Spring configuration Insert picture description here
Insert picture description here
dependency injection

  1. Set injection
  • Dependence: the creation of bean objects depends on the container
  • Injection: all attributes in the bean object are injected by the container
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       default-autowire="byName"
       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-4.2.xsd">
    <bean id="address" class="com.kuang.dao.Address"/>
    <!--使用Spring来创建对象,在Spring这些都成为Bean-->
    <bean id="student" class="com.kuang.dao.Student">
        <!--基本数据类型-->
        <property name="name" value="秦疆"/>
        <!--对象-->
        <property name="address" ref="address"/>
        <!--数组-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
                <value>三国演义</value>
            </array>
        </property>
        <!--list-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>看电影</value>
            </list>
        </property>
        <!--map-->
        <property name="card">
            <map>
                <entry key="身份证" value="1234"/>
                <entry key="银行卡" value="2313"/>
            </map>
        </property>
        <!--set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>
        <!--null-->
        <property name="wife">
            <null/>
        </property>
        <!--Properties-->
        <property name="info">
            <props>
                <prop key="driver">20190525</prop>
                <prop key="url">202.201.5.123</prop>
                <prop key="usrname">root</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>

</beans>

Bean scope
Insert picture description here

  1. Singleton mode
<bean id="student" class="com.kuang.dao.Student" scope="singleton">

All bean objects created by the system point to a value

  1. Prototype mode
<bean id="student" class="com.kuang.dao.Student" scope="prototype">

Every time you get from the container, a new object is generated

The rest of request, session, application can only be used in web development

Bean automatic assembly

  • Auto-wiring is a way for Spring to satisfy bean dependencies
  • Spring will automatically find in the context and automatically assemble properties for the bean

There are three ways of assembly in Spring

  1. Assembly shown in xml
  2. Configure in java
  3. Implicit autowiring bean[important]
<bean class="com.kuang.pojo.Cat"/>
<bean class="com.kuang.pojo.Dog"/>
<!--
	byName:会自动在容器上下文中查找,和自己对象Set方法后面的值对应的beanid!
	byTaoe:会自动在容器上下文中查找,和自己对象属性类型相同的bean!
<bean id="people" class="com.kuang.pojo.People" autowire="byType">
	<property name="name" value="小狂神啊"/>
</bean>
-->

note

  • When byName, you need to ensure that the id of all beans is unique, and the bean needs to be consistent with the value of the set method of the automatically injected property
  • When byType, you need to ensure that the class of all beans is unique, and the bean needs to be consistent with the type of the automatically injected properties

Annotation for automatic assembly

  1. Import annotations
  2. Configuration annotation support
    xmlns:context="http://www.springframework.org/schema/context"
    <context:annotation-config/>

@Autowired
can be used directly on the attribute, or on the set!
Using Autowired, we don’t need to write the Set method. The premise is that your auto-wired property exists in the IOC (Spring) container and matches the name byName.
Note that the
@Nullable field is marked with this annotation, indicating that this field can be null
@Autowired(requeired = false) means that this object can be null, otherwise it is not allowed to be null

If the environment of @Autowired automatic assembly is more complicated, and the automatic configuration cannot be completed by an annotation [@Autowired], we can use @ Qualifier(value=“xxx”) to configure @Autowired when specifying a unique bean object injection

@Resource和@Autowired

  • All are used for automatic assembly, and can be placed on the attribute field
  • @Autowired is implemented by byType, and this object must be required to exist [common]
  • Resource is implemented by byName by default. If the name is not found, it is implemented by byType! If neither can be found, an error will be reported! [Commonly used]
  • Different execution order @Autowired is realized by byType

After using annotations to develop
Spring 4, use annotations to develop, you must import the aop package.

    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.kuang.dao"/>

bean injection

package com.kuang.pojo;

import org.springframework.stereotype.Component;
//@Component等价于<bean id = "user" class="com.kuang.pojo">
@Component
public class User {
    
    
   public String name = "曹晨";
}

The @Componet component indicates that this class is managed by Spring

Attribute annotation

public class User {
    
    
   @Value("曹晨")
   public String name = "曹晨";
}

Derivative annotations
@Component has several derivative annotations. In web development, we will layer them according to the mvc three-tier architecture!

  • dao[@Repository]
  • service[@Service]
  • Controller[@Controller]
    These four annotation functions are the same. They all represent registering a certain class in Spring and assemble the bean

Automatic assembly

  • @Autowired: auto-
    wiring pass type, name If Autowired cannot uniquely auto-wiring attributes, you need to pass @Quantityfier(value="xxx")
    @Nullable: field marked with this annotation, indicating that this field can be null
    @Resource: automatic assembly By name, type

Scope
@scope(value="singleton")

summary

  • xml and annotation
    • XML is more versatile, suitable for any occasion! Maintenance is easier
    • Annotation is not its own class is not available, maintenance is relatively complicated
  • xml and annotation best practices
    • xml is used to manage beans
    • Annotations are only responsible for completing the injection of attributes
    • In the process of using, we only need to pay attention to one problem

Configure Spring using java

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46656833/article/details/113052042