WEB application development -- Explanation of Spring framework annotation + explanation and use of Spring JDBC

Posted by toddmarx on Sun, 20 Feb 2022 04:11:01 +0100

Annotation implementation

Preparation for annotation development

Jar package required for annotation. The annotation function is encapsulated in the AOP package and imported into Spring aop jar

<!--open spring Annotation scanning -->
<context:component-scan base-package="com.qn.spring"/>

spring's annotations on classes include @ Component, @ response, @ Service and @ Controller;
@Autowired and @ Resource are used to modify fields, constructors or setting methods and inject them.

Spring contains four main components for annotation:

    1. @Controller:Controller, recommended to controller Add this annotation to the layer
    2. @Service:Business logic. It is recommended to add this annotation to the business logic layer
    3. @Repository:For warehouse management, it is recommended to add this annotation to the data access layer
    4. @Component:Add this annotation to components that do not belong to the above base level
    @Component(value = "user") //<bean id="user" class="com.qn.spring.model.User"></bean>

Note: Although we artificially add different annotations to different layers, in spring's view, any annotation can be added to any layer

When annotations are used on classes, it indicates that these classes are managed by the spring container. When @ Autowired and @ Resource are used, it indicates that I need a property, method or field, but I don't need to create one myself. Just use annotations, and the spring container will automatically create the properties, methods or objects I need. This is commonly referred to as dependency injection and control inversion.

Annotation injection attribute


@Autowired is an annotation provided by Spring, which can be written on fields and setter methods. If it is written on a field, there is no need to write a setter method. By default, it requires that dependent objects must exist. If null value is allowed, its required property can be set to false

Two ways of injection

1.byType auto injection "this annotation uses the method of automatically assembling beans by type by default

@Autowired//Automatic injection
private Userdao userdao;
//Automatically find this type for automatic injection

2.byName auto injection
If we want to use byName to assemble, we can use it together with @ Qualifier annotation.
The annotation @ Autowired and @ Qualifier need to be used together on the reference attribute@ The value attribute of Qualifier is used to specify the id value of the Bean to be matched

 @Autowired//Automatic injection
    @Qualifier(value = "userdao")
    private Userdao userdao;

3.JDK annotation @ Resource automatic injection
Spring provides support for @ resource annotation in jdk@ Resource annotations can match beans by name or type. Automatically by ByType by default

@Resource(name = "userdao")
private Userdao userdao;

Comparison between annotation and XML

Annotation advantages: convenient, intuitive and efficient (less code and less complex than writing configuration files).
Disadvantages of annotation: it is written into Java code by hard coding, and the modification needs to recompile the code.
The advantage of xml is that the configuration and code are separated. Making modifications in xml does not need to compile the code, but only need to redo
Start the server to load the new configuration.
The disadvantages of xml are: writing is cumbersome, inefficient, and large-scale projects are too complex.

Spring JDBC

Spring is a one-stop framework: spring itself also provides spring MVC in the control layer and Spring JdbcTemplate in the persistence layer

Development steps

1. Download the jar package of Spring JdbcTemplate

   <!-- spring-jdbc -->
        <!-- Alibaba data source -->

2. Import attribute file

  <!--spring Read in properties file-->
    <context:property-placeholder location="config.properties"></context:property-placeholder>

config. The properties configuration is as above

3. Manage data source objects

spring management and database link (data source)

 <!-- to configure druid Database connection object-->
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driverClassName}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${uame}"></property>
        <property name="password" value="${pwd}"></property>
       <!-- <property name="initialSize" value="${initialSize}"></property>
        <property name="maxActive" value="${maxActive}"></property>-->
  <!-- spring provide jdbcTempate encapsulation-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="druidDataSource"></property>

Get the JdbcTemplate in the class

@Repository(value = "userDao")
public class Userdao {
    JdbcTemplate jdbcTemplate;

Common methods in JdbcTemplate

execute: no return value. ddl and add, delete and modify statements can be executed
update: execute new, modify and delete statements;
queryForXXX: execute query related statements;

package com.qn.spring.dao;

import com.qn.spring.model.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Repository(value = "userDao")
public class Userdao {
    JdbcTemplate jdbcTemplate;
@Transactional(propagation = Propagation.REQUIRED)//Communication behavior
    public void save(){
        //spring is used to encapsulate jdbc. By default, transactions are submitted automatically
        jdbcTemplate.update("insert into admin(account,password,sex)values (?,?,?)","jim","111","male");
        System.out.println("Save user");

        //Statement used to execute ddl statement operation on table structure
       /* jdbcTemplate.execute("create table test(id int)");*/

        //jdbcTemplate.queryForObject("select count(*) from admin",Integer.class);
        //Query by serial number
        Admin admin=jdbcTemplate.queryForObject("select * from admin where id=?", new Object[]{4}, new RowMapper<Admin>() {
            public Admin mapRow(ResultSet resultSet, int i) throws SQLException {
                Admin admin1=new Admin();
                return admin1;

        //Collection query
        List<Map<String,Object>> list=jdbcTemplate.queryForList("select *from admin");

        List<Admin> list1=jdbcTemplate.query("select * from admin",  new RowMapper<Admin>() {
            public Admin mapRow(ResultSet resultSet, int i) throws SQLException {
                Admin admin1=new Admin();
                return admin1;

Topics: Java Front-end Spring