Spring summary and configuration file

outline

·In 2002, the prototype of Spring framework was launched for the first time: interface21 framework!

  1. Spring is an open source free framework (container)!
  2. Spring is a lightweight, non intrusive framework!
  3. Inversion of control (IOC), aspect oriented programming (AOP)!
  4. Support transaction processing and framework integration!

IOC

Dependency inversion - LuoTian - blog Park (cnblogs.com)

The idea of dependency inversion principle is IOC (Inversion of Control) control inversion. One implementation method of IOC is DI (Dependency Injection).

Spring configuration file

<?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">

    <!--use Spring To create objects, in Spring In, these are called bean
    Type variable name = new type();
    User user = new User();

        bean = object new User();
    id = Variable name
    class = new Object of;
    property It is equivalent to setting a value for the attribute in the object!

    -->
    <bean id="user" class="com.whirl.User">
            <property name="name" value="cestbon"/>
    </bean>

</beans>

Test implementation

public static void main(String[] args) {
    //Get the context object of Spring
    ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    //Our objects are now managed in Spring. If we want to use them, just take them out directly
    User user = (User)ac.getBean("user");
    //Print
    System.out.println(user.toString());
}

ClassPathXmlApplicationContext

  • Control: who controls the creation of objects? The objects of traditional applications are created by the program itself. After using Spring, the objects are created by Spring.

  • Inversion: the program itself does not create an object, but becomes a passive receiving object.

  • The method of dependency injection is to use set.

  • IOC is a programming idea, which changes from active programming to passive reception. You can browse the underlying source code through the new ClassPathXmlApplicationContext.

  • Now, you don't need to change it in the program. To realize different operations, you only need to modify it in the xml configuration file. The so-called IOC is done in one sentence: objects are created, managed and assembled by Spring!

  • IOC creates objects using parameterless construction by default.

Array subscript assignment is used for those with parameters

<bean id="user" class="com.whirl.pojo.User">
    <constructor-arg index="0" value="cestbon"/>
</bean>

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


    <bean id="address" class="com.whirl.Address">
        <property name="address" value="gfdf"/>
    </bean>

    <bean id="student" class="com.whirl.Student">
        <!--injection address type-->
        <property name="address" ref="address"/>
        <!--String type-->
        <property name="name" value="234"/>
        <!--String type-->
        <property name="books">
            <array>
                <value>JavaSE</value>
                <value>JavaWeb</value>
                <value>Spring</value>
                <value>SpringMVC</value>
                <value>Mybatis</value>
            </array>
        </property>
        <!--List-->
        <property name="hobbies">
            <list>
                <value>sing</value>
                <value>jump</value>
                <value>rap</value>
                <value>Basketball</value>
            </list>
        </property>
        <!--Map-->
        <property name="card">
            <map>
                <entry key="435" value="dasd"></entry>
                <entry key="123" value="ewq"></entry>
            </map>
        </property>
        <!--set-->
        <property name="games">
            <set>
                <value>sing</value>
                <value>jump</value>
                <value>rap</value>
                <value>Basketball</value>
            </set>
        </property>
        <!--String-->
        <property name="wife" value="xxx"></property>
        <!--Properties-->
        <property name="info">
            <props>
                <prop key="p1">v1</prop>
                <prop key="p2">v2</prop>
                <prop key="p3">v3</prop>
            </props>
        </property>
    </bean>

</beans>

Spring auto assembly

ByName method auto assembly

  1. autowire="byName"
  2. It will automatically find the bean id corresponding to the value behind the set method of its own object in the container context!
  3. Disadvantages: the value after the set method is the same as the id
<bean id="cat" class="cn.bloghut.domin.Cat"/>
<bean id="dog" class="cn.bloghut.domin.Dog"/>

<!--
    byName: It will automatically find its own objects in the container context set The value after the method corresponds to bean id!

-->
<bean id="people" class="cn.bloghut.domin.People" autowire="byName">
    <property name="name" value="csdn_balderdash"/>
</bean>

public static void main(String[] args) {

    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    People people = ac.getBean("people", People.class);

    people.getCat().shout();
    people.getDog().shout();

}
  1. autowire="byType"
  2. It will automatically find bean s with the same object attribute type in the container context
  3. Disadvantages: it must ensure that the type is globally unique (only one in the IOC container).
<bean id="cat" class="cn.bloghut.domin.Cat"/>
<bean id="dog11" class="cn.bloghut.domin.Dog"/>
   <!--
    byType: It will automatically find the object with the same property type as its own object in the container context bean

-->
  <bean id="people" class="cn.bloghut.domin.People" autowire="byType">
      <property name="name" value="csdn_balderdash"/>
  </bean>
public static void main(String[] args) {

    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    People people = ac.getBean("people", People.class);

    people.getCat().shout();
    people.getDog().shout();

}

Summary:

byName, the id of all beans needs to be unique, and the bean needs to be consistent with the value of the set method of the automatically injected attribute
When     byType, it is necessary to ensure that the class of all beans is unique, and the bean needs to be consistent with the type of the automatically injected attribute

Annotation for automatic assembly

xml header file constraints

<?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"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--Enable annotation scanning-->
    <context:component-scan base-package="com.whirl"/>

   <!--Enable annotation support-->
   <context:annotation-config/>
</beans>

@Autowired

  1. Use on properties
  2. Use in set mode
  3. Using Autowired, you don't need to write the set method. The premise is that your auto assembled attribute exists in the IOC (Spring) container (it needs to be injected into the container through other ways) and conforms to the name byName.

@Componet

Equivalent to < bean id = "user" class = "CN. Blogout. Domain. User" >

@Configuration

It is essentially a @ Componet, so it will also be loaded by Spring. See gossip blog for details

AOP

Based on native API

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>
public class Log implements MethodBeforeAdvice {

    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+" of "+method.getName()+"Method executed");
    }
}

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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">


    <!--register bean-->
    <bean id="userService" class="cn.bloghut.service.UserServiceImpl"/>
    <bean id="afterLog" class="cn.bloghut.log.AfterLog"/>
    <bean id="log" class="cn.bloghut.log.Log"/>

    <!--Method 1: use native Api Interface-->
    <!--to configure aop-->
    <aop:config>
        <!--1.Configure pointcuts  pointcut breakthrough point expression expression, execution(Location to execute!)-->
        <!-- Where does the pointcut execute your code-->
        <aop:pointcut id="pointcut" expression="execution(* cn.bloghut.service.UserServiceImpl.*(..))"/>

        <!--Execute surround increase!-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

    </aop:config>

</beans>

Section mode

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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">


    <!--register bean-->
    <bean id="userService" class="cn.bloghut.service.UserServiceImpl"/>
    <bean id="diyPointCut" class="cn.bloghut.diy.DiyPointCut"/>

    <!--Method 1: use native Api Interface-->
    <!--to configure aop-->
    <aop:config>
        <!--1.Configure pointcuts  pointcut breakthrough point expression expression, execution(Location to execute!)-->
        <!-- Where does the pointcut execute your code-->
        <aop:pointcut id="pointcut" expression="execution(* cn.bloghut.service.UserServiceImpl.*(..))"/>

        <!--Self defined section ref Class to reference-->
        <aop:aspect id="aspect" ref="diyPointCut">
            <!--Before method execution method: Cut in method pointcut: breakthrough point -->
            <aop:before method="before" pointcut-ref="pointcut"/>
            <!--After method execution-->
            <aop:after method="after" pointcut-ref="pointcut"/>
        </aop:aspect>

    </aop:config>

</beans>

Annotation method

  • Note: enable annotation aop support
  • <aop:aspectj-autoproxy/>
<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--register bean-->
    <bean id="userService" class="cn.bloghut.service.UserServiceImpl"/>

    <bean id="annotationPointcut" class="cn.bloghut.annotation.AnnotationPointcut"/>

    <!--open aop Annotation support-->
    <aop:aspectj-autoproxy/>

</beans>

Spring integrates Mybatis

rely on

<dependencies>
    <!--unit testing -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>
    <!--mysql drive-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <!--mybatis package-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <!--spring of context core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.0.RELEASE</version>
    </dependency>
    <!--Spring If you operate the database, you also need one spring-jdbc-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
    <!--Aop support-->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.8.13</version>
    </dependency>
    <!--mybatis integration spring Dependence of-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>
    <!--setter Construction method plug-in-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.10</version>
    </dependency>
</dependencies>

data source

<!--
    DataSource: use Spring Data source replacement for Mybatis Configuration of c3p0 dbcp druid
    use Spring Provided JDBC org.springframework.jdbc.datasource.
-->

<!--Configure data source-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
    <property name="username" value="root"/>
    <property name="password" value="123"/>
</bean>

2.sqlSessionFactory
<!--to configure sqlSessionFactory factory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!--binding mybatis Configuration file for-->
    <property name="mapperLocations" value="classpath:cn/bloghut/mapper/*Mapper.xml"/>
    <!--Configure alias-->
    <property name="typeAliases" value="cn.bloghut.domain.User"/>
</bean>

3.sqlSessionTemplate
<!--SqlSessionTemplate namely sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <!--Only constructor injection can be used sqlSessionFactory,Because it doesn't set method-->
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--
        DataSource: use Spring Data source replacement for Mybatis Configuration of c3p0 dbcp druid
        use Spring Provided JDBC org.springframework.jdbc.datasource.
    -->

    <!--Configure data source-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="123"/>
    </bean>

    <!--to configure sqlSessionFactory factory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--binding mybatis Configuration file for-->
        <property name="mapperLocations" value="classpath:cn/bloghut/mapper/*Mapper.xml"/>
        <!--Configure alias-->
        <property name="typeAliases" value="cn.bloghut.domain.User"/>
    </bean>

    <!--SqlSessionTemplate namely sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--Only constructor injection can be used sqlSessionFactory,Because it doesn't set method-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <!--==============================Transaction configuration start==============================-->

    <!--Configure declarative transactions-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--combination AOP Implement transaction weaving-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
           <!--Which methods are configured with transactions-->
            <!--Configure the propagation characteristics of transactions:
                propagation
                read-only="true" read-only
            -->
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="find" read-only="true"/>

            <!--Configure transactions for all methods-->
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--Configure transaction entry-->
    <aop:config>
        <!--Configure pointcuts-->
        <aop:pointcut id="txPointcut" expression="execution(* cn.bloghut.mapper.*.*(..))"/>
        <!--Cut in transaction-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>

    <!--==============================End of transaction configuration==============================-->

</beans>

applicationContext.xml and UserMapper configuration files

<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring-dao.xml"/>

   <bean id="userMapper" class="cn.bloghut.mapper.impl.UserMapperImpl">
       <property name="sqlSession" ref="sqlSession"/>
   </bean>


</beans>


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.bloghut.mapper.UserMapper">
    <select id="findAll" resultType="cn.bloghut.domain.User">
        select * from user;
    </select>

    <insert id="add" parameterType="cn.bloghut.domain.User">
    insert into user(username,password,perms) values (#{username},#{password},#{perms})
    </insert>

    <delete id="delete" parameterType="int">
    delete form user where id = #{value}
    </delete>

</mapper>

Keywords: Java Spring Back-end

Added by binit on Sun, 30 Jan 2022 21:13:09 +0200