In Spring, there are many efficient annotations, which simplifies development and improves code readability, so that we don't need to go again
It 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
@Component
Annotation, 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 (
@ComponentScan
or<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:
@Service
yes@Component
Derived 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
@Component
Uses the same -
Configuration: with
@Component
Same as using configuration class or XML file@Service("adminService") public class AdminServiceImpl implements AdminService { ... }
@Repository
-
effect:
@Repository
It is another derived annotation of @component, which is used to mark the data access layer (DAO) -
Usage: with
@Service
consistent, special@Repository
It 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
@Autowired
It 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@Autowired
That’s it
@Qualifier
-
@Qualifier
For@Autowired
Used together, when there are multiple beans of the same type, they can be provided@Qualifier
To 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
@Resource
Beans can be injected, but usually by name, which is the same as@Autowired
There are similarities, but there are differences in the injection methods
Inject by name
-
This is
@Resource
The default injection method, it will find a bean with the same name and target attribute name in the container, and inject itpublic class AdminServiceImpl implements AdminService { @Resource(name = "adminDao") private AdminDao adminDao; }
In this example,@Resource(name = "adminDao")
will be based onadminDao
The name of the name is injects the correspondingAdminDao
Implementation class
Inject by attribute
-
If the name attribute is not specified,
@Resource
It 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 is
AdminDao
Type of Bean, Spring will automatically inject it intoadminDao
In the attribute
@Resource
and@Autowired
difference
-
@Autowired
Inject by default, you can use it@Qualifier
Let's specify the name of a specific bean to solve the problem of the Drops of Republican Bean -
@Resource
By default, it is injected by name. If the name is specified, it is injected by type.
@PostConstruct
and@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
@Configuration
and@ComponentScan
-
@Configuration
Function: The class identified using this annotation indicates that this class is aSpring
Configuration class. Compared with the traditional configuration file using XML files, this configuration classSpring
The configuration class usually includes the definition of the bean, and the method of configuring the bean and registering it with the Spring container. -
@ComponentScan
Role: 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 {
}
@PropertySource
and@Value
@PropertySource
- effect:
@PropertySource
Used to configure Spring to load.properties
document
@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.
@PropertySource
Use together, pass${}
Grammar reference.properties
key-value pairs inComponent @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:
@Bean
The 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:
name
The 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);
}
@Bean
Annotation methodgetConnection()
ReturnConnection
Object will be registered as bean in Spring container, you can pass()
Come to get it