Creating Objects/Common Annotations Using Annotation Annotation

When using xml declaration method to create objects, it is easy to cause too much code declared in the configuration file, which is not conducive to later code maintenance. Annotation annotations provided in spring can be used to solve this problem.

1. Create objects using <context: component-scan base-package=">

The purpose of the configuration code is to fill the specified package with classes that match the created object. If some classes need to be instantiated by spring, the @Compent annotation must be used above the class class class.

The configuration file is as follows: Note that the following three lines of code ending in context are configurations that must be added using annotations

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <context:component-scan base-package="com.spring.service"></context:component-scan>


2. Use Component to identify classes

The function of annotation @Component is to identify a class as a component that can be identified by <context: component-scan base-package="> scanner and automate the instance. Finally, the instance object is put into the DI container.

package com.spring.service;

import com.spring.dao.MyUser;
import com.spring.dao.MyUserimpl;
import com.spring.entity.User;
import org.springframework.stereotype.Component;


public class UserServiceimpl implements UserService {

    public void add() {
        System.out.println("Add a user");
    public void add(User user) {
        System.out.println(" service Add a user"+user);

At this point, the method getBean (class. class) gets the object.

When there are multiple scannable components of the same type, confusion may occur, and @Component ("bean ID") can be chosen.


getbean("bean ID") when the object is retrieved


web development, commonly used annotations
@ Repository: Acts like @Compenent. But @Repository is mainly used for the DAO layer and @Compenent is mainly used to declare some common components.
@ Service: Declare the service layer
@ Controller: Declare the action//controller layer
@ Autowired: Autowired is automatically injected according to attributes, written in the class before the attributes that need to be injected.
@ Qualifier: When you have multiple classes of the same type, you can inject them according to id.
For example, in the service layer
Specify the injection id in actioin for injection

    private UserServiceimpl userServiceimpl;

At this point, because automatic injection is designed to multiple packages (DAO layer, Service layer, etc.), when creating objects with <context: component-scan base-package="> in the configuration file, the package name written must contain all the packages involved (otherwise error will be reported).
Welcome to correct!

Tags: Spring xml encoding Web Development

Posted on Sat, 07 Sep 2019 00:40:04 -0700 by sargus