Location>code7788 >text

Spring common annotations

Popularity:204 ℃/2025-01-25 15:13:24

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 tags in files

Annotation of creating 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

    // By default, change the ID name to a lowercase
     // Use the value attribute to modify
     @Component (Value = "A")
     @Component ("s")
     @Component
     Public Class Admin Implements Serializable {
     Elastic
     }
  • Configuration method

    Enable component scanning in configuration classes or XML configuration files (@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), indicating that this class is a service component, which is more well-known, indicating that it is a Bean of the service layer

  • Usage: with@ComponentSame usage

  • 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: and@Serviceconsistent, special@RepositoryIt is for the persistence layer

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

@Controller

  • Function: @Controlller is an annotation used to mark the Spring MVC controller class. It indicates that the class is a Web controller. It is used to process requests and return views.

  • 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

  • @Qualifierused with@AutowiredUse together, when there are multiple types of bean, you can provide it@QualifierLet's 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

@ResourceYou can inject bean, but it is usually injected according to the name, which@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 is injected into the correspondingAdminDaoImplementation class

Inject by attribute

  • If there is no specified name attribute,@Resourcewill be automatically injected according to the type of the attribute, that is, if@ResourceThe annotation target matches a certain type in the container, and it will automatically inject this type of bean

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

    In this example, if there isAdminDaoType Bean, Spring will be automatically injectedadminDaoin properties

@Resourceand@AutowiredDifference

  • @AutowiredInjected by type by default, can be used@QualifierTo specify a specific Bean name to solve the problem of Dioh Gonghe Bean
  • @ResourceInject it by default by the name, if it is specified Name, inject it according to the type.

@PostConstructand@PreDestroy

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

  • usage:

    • @PostConstruct:This method is called when the Bean is re-created and all dependency injections are completed.
    • @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 notes

@Configurationand@ComponentScan

  • @ConfigurationRole: The class that uses this annotation identification indicates that this class is a classSpringConfiguration 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 classIt is equivalent to importing the contents of another configuration class, which can be imported into multiple configuration classes
@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 class path of the change file 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.@PropertySourceused together, through${}Grammar reference.propertiesThe key value pair

    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 a Spring Bean and placed in the 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()ReturnConnectionThe object will be registered as a Bean in the Spring container. You can pass()to get it