Introduction to Pure Annotation Mode

Pure annotation mode means completely avoiding XML configuration files, instead using Java annotations (Annotation) to implement IoC container configuration and management. This approach has been recommended since Spring 3.x and is more in line with Java coding habits, making it easier to maintain and understand.

Main Annotations Introduction

Configuration

Marks a class as a Spring configuration class, replacing XML configuration files. This class will be loaded by the IoC container as a configuration class.

ComponentScan

Specifies the base package path for Spring to scan components, thereby automatically registering Beans that meet the criteria. By default, scans the current class’s package and sub-packages.

Bean

Declares a regular Java object as a Bean in the Spring container. Similar to the <bean> tag in XML files, suitable for third-party classes or classes whose source code cannot be directly modified.

Component, Service, Repository, Controller

These annotations are used to register classes as Beans in the Spring container, each suitable for different layers:

  • Component: General-purpose component annotation
  • Service: Business logic layer component annotation
  • Repository: Persistence layer component annotation
  • Controller: Controller layer component annotation, handling Web requests

Autowired

  • Automatically injects dependent objects, using byType injection
  • Can be used on constructors, fields, Setter methods, etc.

Qualifier

  • Used to resolve Bean name conflicts in dependency injection
  • Used together with Autowired to specify a specific Bean name

Primary

When multiple candidate Beans exist, the Bean marked as Primary is preferentially selected.

Scope

Specifies the Bean scope. Common ones:

  • singleton (default): Only one instance created in the container
  • prototype: A new instance created for each request
  • request: One instance created per HTTP request (Web application)
  • session: One instance created per HTTP session (Web application)

Advantages

  • No XML configuration: More concise configuration, matching Java code style
  • Type safety: Avoids string-based XML configuration, improving code security
  • Better IDE support: Easier to refactor or search
  • Easier testing: Annotations make it easy to create Mock components for unit testing

Precautions

  • If component scanning (ComponentScan) is not enabled, all Beans need to be manually registered
  • Annotations rely on Spring context scanning and parsing, ensuring package paths are correctly configured
  • Multiple candidate Beans may cause injection conflicts, need to use Primary or Qualifier to resolve

Pure Annotation Mode Implementation

Transform the XML + annotation mode, migrate all content remaining in XML out, and finally remove XML.

Corresponding annotations:

  • ComponentScan replaces context:component-scan in XML
  • Configuration indicates the current class is a configuration class

Configuration Files

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1">
  <context-param>
    <param-name>contextClass</param-name>
    <!-- Annotation method -->
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <!-- Configuration class -->
    <param-value>wzk.SpringConfig</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://172.16.1.130:3306/wzk-mybatis
jdbc.username=hive
jdbc.password=hive@wzk.icu

SpringConfig Configuration Class

In the startup configuration class, scanning is done through annotations:

@ComponentScan({"wzk"})
@Configuration
@PropertySource({"classpath:jdbc.properties"})
public class SpringConfig {

    @Value("${jdbc.driver}")
    private String driverClassName;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource createDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }
}

WzkConnectionUtils Utility Class

For database connections, also let Spring manage:

/**
 * Current thread SQL connector
 * Uses ThreadLocal to pass connection
 * @author wzk
 * @date 16:43 2024/11/18
**/
@Component
public class WzkConnectionUtils {

    private final ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    @Autowired
    private DataSource dataSource;

    public Connection getCurrentConnection() throws SQLException {
        Connection connection = threadLocal.get();
        if (null == connection) {
            connection = dataSource.getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }
}

Test Run

The program test runs normally.