Introduction to Spring and IOC

Introduction of the Spring

Rod Johnson, founder of the Spring Framework, is a well-known author. It’s hard to imagine that Rod Johnson’s degree, which really surprised a lot of people, was a PhD from the University of Sydney, but his major was not computer science, but musicology. Spring concept: makes existing technologies easier to use and is itself a hodgepodge of existing technology frameworks! SSH: Struct2 + Spring + Hibernate! SSM: SpringMVC + Spring + MyBatis! Dependency import:

< the dependency > < groupId > org. Springframework < / groupId > < artifactId > spring - webmvc < / artifactId > < version > 5.3.5 < / version > </dependency>

Conclusion: Spring is a lightweight Inversion of Control (IOC) and Aspect Oriented Programming (AOP) framework

Inversion of Control (IoC) : In the past, the programmer had to take the initiative in the program, and the user had to change the requirements of the program. The IoC changed this method, and put control in the user’s hands. This greatly decouples the application, allowing the programmer to focus more on the business layer

IOC creation and key configuration

Create a Maven project, import dependencies, and write entity classes

@Data
public class Student {
    private String name;
    private int id;

Writing XML Files

<? The 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"> <! Entity class mapping --> <! By default, create objects using the constructor without arguments. -- To use a parameter, Class =" com.song-pojo. student" > <constructor-arg ="name" value="mike"/> <constructor-arg ="mike"/> <constructor-arg ="name" value="mike"/> <constructor-arg name="id" value="2"/> <property name="name" value="hehe"/> </bean> <! -- <bean id="..." class="..." >--> </beans>

test

public class myTest { @Test public void test(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); Student student = (Student) applicationContext.getBean("student"); System.out.println(student.toString()); }}

Consider: How are objects created? Spring creates objects automatically, and the Spring container assigns attributes to the object. This process is called inversion of control: who controls the creation of the object. In a traditional application, the object is created by the program itself. Inversion: The program itself does not create objects. Instead, it passively accepts objects created by the Spring container. The container uses set methods to inject property values into objects created, managed, and assembled by Spring.

Spring key configuration!

<! Class: bean class: bean class name: package name + class name: bean class name: package name + class name --> <bean id="userT" class="com.kuang.pojo. userT" name="user2 u2,u3; U4 "> <property name="name" value=" "/> </bean> <import resource= ben.xml />

Dependency injection and auto-loading beans

When a complex property of an entity class appears, it looks like this:

@Data public class Person { private String name; Private Cat Cat; Private String[] books; Private List<String> hobbies; Private Map<String,String> card; Private Set<String> games; // private String Wife; // private Properties Info; // private Dog Dog; }

Reference injection cat

<! - refer to ref - > < property name = "cat" ref = "cat" / > < bean id = "cat" class = "com. Pojo. Cat" / >

An array of books

<! - array 'arry - > < property name = "books" > < array > < value > Java core technology < / value > < value > introduction to the JVM value > < / < value > database entry to the grave value > < / <value> </value> </array> </property>

List and set hobbies games

<! -- list <property name="hobbies"> <list> <value> </value> </value> <value>rap</value> </list> </property>

When set, change the keyword

The map collection card

<! -- Map --> <property name="card"> < Map > <entry key=" 5206565656565"/> <entry key=" card" value="111111111111111"/> </map> </property>

null wife

<! -- null--> <property name="wife"> <null/> </property>

properties info

<property name="info">
           <props>
               <prop key="url">https//www.baidu.com</prop>
               <prop key="driver">https//www.baidu.com</prop>
           </props>
       </property>

Autowire Bean

When an entity class has a reference to another class, we usually use ref to refer to another Bean in XML. This method is cumbersome, as follows:

<bean id="student" class="com.song.Student"> <property name="name" value="mike"/> <property name="sex" value=" male "/> <property name="dog" ref="dog"/> <property name="cat" ref="cat"/> </bean> <bean id="dog" class="com.song.Dog"/> <bean id="cat" class="com.song.Cat"/>

There are two main types of autowire: XML autowire and annotation autowire

The XML simply adds the autowire tag to the bean tag

Summary:

ByName (), the bean ID must be unique, and the bean must match the value of the set method of the autoinjected property! The class of all beans is unique, and the type of the bean should be the same as that of the automatically injected property.

Import Annotations Configuring Annotations Support Using @Autowire Annotations XML Constraints and Annotations Support:

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

Using annotations

@Value(" private String Name "); private String sex; @Autowired private Dog dog; @Autowired private Cat cat;

Using @Resource(built-in to Java), do the same as above,

@Autowired precedes byType,@Resource precedes byName and byType

Developing with annotations (Improtant)

1. Import AOP package and constraint AOP package are imported together when Spring WebMVC is imported

<? The 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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd "> / / scan package under the annotation < context: component - scan base-package="com.song"/> <context:annotation-config/> </beans>

AOP

Aspect Oriented Programming (AOP) :Aspect Oriented Programming (AOP) is an abbreviation of Aspect Oriented Programming. It dynamically inserts a program execution into a tangent point during the program running, and realizes the addition of functions without changing the source program.

Advantage: With AOP, we can define intersecting relationships and apply those relationships to cross-module object models that differ from each other. AOP also allows us to layer functionality rather than embed it, making the code more readable and easier to maintain. It will work well with object-oriented programming.

AOP in Spring:

Spring API interface to implement AOP:

Interface method:

1. Import AspectJWeaver dependencies

< the dependency > < groupId > org. Aspectj < / groupId > < artifactId > aspectjweaver < / artifactId > < version > 1.9.6 < / version > </dependency>

2. Write interfaces and implementation classes

Public void addBook(); public void addBook(); public void deleteBook(); public void selectBook(); public void updateBook(); }
Public class BookDaOImpl implements BookDao {public void addBook() {System.out.println(); public class BookDaOImpl implements BookDao; } public void deleteBook() {System.out.println(); public void deleteBook() {System.out.println(); } public void selectBook() {System.out.println(" A book has been found "); } public void updateBook() {System.out.println(" UpdateBook "); }}

The function to be inserted into the incision

public class Log implements MethodBeforeAdvice { //method: Method of the target object to execute //args: parameter //target: Public void before(Method Method, Object[] objects, Object o) throws Throwable {System.out.println(O.getClass ().getName()+ Method.getName ()+"); }}

3. Write XML files

<? The 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: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/aop https://www.springframework.org/schema/aop/spring-aop.xsd "> <bean id="bookDaoImpl" class="com.song.service.BookDaoImpl"> </bean> <bean id="log" class="com.song.log.Log"/> <! -- config-config-ibb0 <aop: config-> <! -- config-ibb0 <! Breakthrough point -- - > < aop: pointcut id = "pointcut expression" = "execution (* com. Song. Service. BookDaoImpl. * (..) ) "/ > <! > <aop:advisor advice-ref="log" pointcut-ref="pointcut"/> </aop:config> </beans>

4. Test:

public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); // The proxy class represents an interface rather than an implementation BookDAO BookDAO = (BookDAO) Context.getBean (" BookDAOImpl "); bookDaoImpl.addBook(); }

Results:

Second way: Customize the section class

1. Custom notification class

Public void before(){System.out.println(); public void before(){System.out.println(); } public void after(){System.out.println();} public void after(){System.out.println(); }}

2, the XML

<aop:config> <aop:aspect ref="aspect"> <aop:pointcut id="point" expression="execution(* com.song.service.BookDaoImpl.*(..) ) "/ > <! > <aop:before method="before" pointcut-ref="point"/> <aop:after method="after" pointcut-ref="point"/> <aop:after method="after" pointcut-ref="point"/> </aop:aspect> </aop:config>

3, test,

The third way: annotation way!

Very simple; Tag section class – Tag notification – configures XML to enable annotation support

@Aspect public class AspectAnoation { @Before("execution(* com.song.service.BookDaoImpl.*(..) )") public void before(){System.out.println(); } @After("execution(* com.song.service.BookDaoImpl.*(..) )") public void after(){System.out.println(); }}
<bean id="AspectAnoation" class="com.song.diy.AspectAnoation"/> <! > <aop:aspectj-autoproxy/>

Integration of Mybatis

MyBatis simple review

General configuration file — > write entity class — > write interface — > write interface corresponding XML file — > test 1, import all dependencies: The Lombok package is also imported here. In addition, the Lombok package is also imported here. In addition, the Lombok package is imported here. Configure Maven static resource filtering issues!

<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < dependencies > <! -- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <dependency> <groupId> MySQL </groupId> < artifactId > mysql connector - Java < / artifactId > < version > 8.0.24 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId> org.springFramework </groupId> </artifactId> spring-jdbc</artifactId> <version>5.3.5</version> </dependency> <! -- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> The < artifactId > aspectjweaver < / artifactId > < version > 1.9.6 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis spring</artifactId> <version>2.0.6</version> </ Dependencies > <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build> </project>

2. Entity classes

@Data
public class User {
    private int userId;
    private String userName;
    private String password;
    private String sex;
    private String email;
}

3. Interface and corresponding configuration files

public interface UserMapper {
    List<User> getUser();
}

<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE mapper PUBLIC "- / / mybatis.org//DTD mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < mapper namespace="com.song.mapper.UserMapper"> <select id="getUser" resultType="com.song.pojo.User"> select * from users </select> </mapper>

4, MyBatisConfig configuration file

<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE configuration PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/testweb?userSSL=true&amp; useUnicode=true&amp; characterEncoding=UTF-8&amp; serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/song/mapper/UserMapper.xml"/> </mappers> </configuration>

5. Toolkit:

public class MybatisUtil { //sqlSessionFactory --> sqlSession static SqlSessionFactory sqlSessionFactory = null; Static {try {// SqlSessionFactory object String resource = "myBatisConfig. XML "; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); }} // The SQLSessionFactory provides all the methods needed to execute SQL commands in the database. public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); }}

6. Test:

   @Test
    public void test(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.getUser();
    }

Integration Mode 1

Aerial view: Spring-MyBatis

The following is the corresponding code for the procedure

<? The 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: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/aop https://www.springframework.org/schema/aop/spring-aop.xsd "> <! - 2, data source - > < bean id = "dataSource" class = ". Org. Springframework. JDBC dataSource. DriverManagerDataSource "> < property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="username" value="root"/> <property name="url" value="jdbc:mysql://localhost:3306/testweb? userSSL=true&amp; useUnicode=true&amp; characterEncoding=UTF-8&amp; serverTimezone=UTC"/> <property name="password" value="123456"/> </bean> <! - 3, SqlSessionFactoryBean project - > < bean id = "sqlSessionFactory" class = "org. Mybatis. Spring. SqlSessionFactoryBean" > < property  name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatisConfig.xml"/> <property name="mapperLocations" value="classpath:com/song/mapper/*.xml"/> </bean> <! - 4, injection - > < bean id = "sqlSession" class = "org. Mybatis. Spring. SqlSessionTemplate" > < constructor - arg index = "0" ref="sqlSessionFactory"/> </bean> <! - 6, registered bean - > < bean id = "userMapper" class = "com. Song. Mapper. UserMapperImpl" > < property name = "sqlSessionTemplate" ref="sqlSession"/> </bean> </beans>

Implementation class:

Public class UserMapPerImpl implements UserMapper {// SQLSession private SQLSessionTemplate sqlSessionTemplate; Public void setSessionTemplate (SQLSessionTemplate SQLSessionTemplate) {this.SQLSessionTemplate = sqlSessionTemplate; }

Integration mode three:

As with the first four steps of method 2, step 5 does not create a private method, but instead inherits a class and calls a class method to get an SQLSession. The same principle applies to the class:

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper { public List<User> getUser() { return getSqlSession().getMapper(UserMapper.class).getUser(); }}

bean:

    <bean id="userMapper2" class="com.song.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

The last

At the end of the article, the author sorted out a lot of data for you! Include JAVA core knowledge + a full set of architect learning materials and video + front-line big factory interview bible + interview resume template + ali Meituan netease Tencent Xiaomi iQIYI quick hand BiliBili interview questions +Spring source collection + JAVA architecture practical ebook and so on!

Welcome to pay attention to the public number: the future has light, receive!