Location>code7788 >text

Introduction to Spring common annotations

Popularity:570 ℃/2025-01-25 19:12:50

In Spring, there are many efficient annotations, which simplifies development and improves code readability, so that we don't need to go againIt is very convenient to write labels in the file

Create annotations for objects

In Spring, Bean, which is used to identify different types, enables the Spring container to automatically manage the creation and life cycle of these beans

@Component

  • Role: Mark a class as a bean managed by Spring container, Spring will automatically scan and create the object

  • Usage: used on classes@ComponentAnnotation, Spring will automatically register as a Bean

    //Change the id name to lowercase by default
     //can be modified using the value attribute
     //@Component(value = "a")
     //@Component("s")
     @Component
     public class Admin implements Serializable {
     ...
     }
  • Configuration method

    Enable component scan in the configuration class or XML configuration file (@ComponentScanor<context:componet-scan>Label

    • Java configuration method

      @Configuration
      @ComponentScan(basePackages = "")
      public class AppConfig {
      }
      
      
    • XML configuration method

      <!--Spring will scan all classes under the base-package path-->
           <context:component-scan base-package=""></context:component-scan>

@Service

  • effect:@Serviceyes@ComponentDerived annotation ofMainly used for the class of business layers (serviceimp)It means that this class is a service component, and it is more well -known, indicating that it is the bean of the service layer

  • Usage: and@ComponentUses the same

  • Configuration: with@ComponentSame as using configuration class or XML file

    @Service("adminService")
    public class AdminServiceImpl implements AdminService {
    ...
    }
    

@Repository

  • effect:@RepositoryIt is another derived annotation of @component, which is used to mark the data access layer (DAO)

  • Usage: with@Serviceconsistent, special@RepositoryIt is for the persistence layer

    @Repository
    public class UserRepository {
       ...
    }
    
    
  • Configuration method: Enable component scanning in the configuration class, or use XML configuration

@Controller

  • Role: @Controlller is used to mark the annotation of the Spring MVC controller class. It indicates that this class is a web controller.

  • Usage: Used with Spring MVC to handle HTTP requests

    @Controller
    public class UserController {
     ....
    }
    
    

Annotation of the injection object

@Autowired

@AutowiredIt is the most commonly used annotation, used to automatically inject beans in the Spring container into the current class.

@Service("adminService")
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminDao adminDao;
}

Add to the fields that need to be injected@AutowiredThat’s it

@Qualifier

  • @QualifierFor@AutowiredUsed together, when there are multiple beans of the same type, they can be provided@QualifierTo specify the specific injected Bean
@Repository
public class ClassDao1 extends ClassDao{}
@Repository
public class ClassDao2 extends ClassDao{}

@Autowired
@Qualifier("classDao1")
private ClassDao classDao;

public void queryAll() {
    ();
    (classDao);
}

@Resource

@ResourceBeans can be injected, but usually by name, which is the same as@AutowiredThere are similarities, but there are differences in the injection methods

Inject by name

  • This is@ResourceThe default injection method, it will find a bean with the same name and target attribute name in the container, and inject it

    public class AdminServiceImpl implements AdminService {
        @Resource(name = "adminDao")
        private AdminDao adminDao;
    }
    

In this example,@Resource(name = "adminDao")will be based onadminDaoThe name of the name is injects the correspondingAdminDaoImplementation class

Inject by attribute

  • If the name attribute is not specified,@ResourceIt will automatically inject according to the type of attribute, that is, if, if, if@Resource, the target of the annotation matches a certain type in the container, and it will automatically inject a bean of that type.

    public class AdminServiceImpl implements AdminService {
        @Resource
        private AdminDao adminDao;
    }
    

    In this example, if there isAdminDaoType of Bean, Spring will automatically inject it intoadminDaoIn the attribute

@Resourceand@Autowireddifference

  • @AutowiredInject by default, you can use it@QualifierLet's specify the name of a specific bean to solve the problem of the Drops of Republican Bean
  • @ResourceBy default, it is injected by name. If the name is specified, it is injected by type.

@PostConstructand@PreDestroy

The two annotations are the methods that are executed after the initial and destroy

  • usage:

    • @PostConstruct: When bean is created again and all dependencies are injected, call this method
    • @PreDestroy:This method is called before the Bean is destroyed
    @Component
    public class UserService {
    
        @PostConstruct
        public void init() {
            ("UserService is initialized");
        }
    
        @PreDestroy
        public void destroy() {
            ("UserService is destroyed");
        }
    }
    

Other configuration annotations

@Configurationand@ComponentScan

  • @ConfigurationFunction: The class identified using this annotation indicates that this class is aSpringConfiguration class. Compared with the traditional configuration file using XML files, this configuration classSpringThe configuration class usually includes the definition of the bean, and the method of configuring the bean and registering it with the Spring container.
  • @ComponentScanRole: Used forSpecify the packages that should be scanned when Spring initializes the container and register the classes in the packages as beans.Its function is similar to that in XML files<context:component-scan/>Label
@Configuration
 @ComponentScan("")
 //@ComponentScan({""}) method to configure multiple paths
 public class SpringConfig {

 }

@Import

  • Function: This annotation canUsed to introduce other configuration classes into the current configuration class, which is equivalent to importing the content of another configuration class into the current class. Multiple configuration classes can be imported.
@Configuration
@ComponentScan("")
@Import({, })
public class SpringConfig {

}

@PropertySourceand@Value

@PropertySource

  • effect:@PropertySourceUsed to configure Spring to load.propertiesdocument
@Component
@PropertySource("classpath:")
public class JDBCUtil {
...
}
  • classpath: Used to receive the classpath of the file located in the project

@Value

  • Function: It is used to inject the value in the configuration file into the Spring Bean field. The method parameter or constructor.@PropertySourceUse together, pass${}Grammar reference.propertieskey-value pairs in

    Component
    @PropertySource("classpath:")
    public class JDBCUtil {
        @Value("${driverClassName}")
        private String driver;
    
        @Value("${url}")
        private String url;
    
        @Value("${accountName}")
        private String accountName;
    
        @Value("${password}")
        private String password;
    
      
    }
    

@Bean

  • effect:@BeanThe annotation isThe effect is based on a method,The return value of the identified method will be registered as Spring Bean and put it into a container.
  • property:nameThe attribute is used to specify the id of the Bean. If not specified, it defaults to the method name.
@Bean
    public Connection getConnection() throws SQLException {
        return (url, accountName, password);
    }

@BeanAnnotation methodgetConnection()ReturnConnectionObject will be registered as bean in Spring container, you can pass()Come to get it