Using annotation development

  • After spring 4, if you want to develop with annotations, you must ensure that the AOP package is imported
  • To use annotations, you need to import context constraints and add annotation support

Through a small deemo explanation, the structure is shown in the figure
Using annotation development

Applicationcontext.xml configuration information is

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    <!-- Specify the package to be scanned, and the annotations under the package will take effect -- >
    <context:component-scan base-package="com.hudu"/>

<!--    <bean id="user" class="">-->
<!--        <property name="name" value="hudu"/>-->
<!--    </bean>-->


Using annotation development, the entity class configuration is as follows

//Equivalent to < bean id = "user" class = "com. Com. Hudu. POJO. User" / >
//@Component component
public class User {
    //Equivalent to < property name = "name" value = "hudu" / >, or on the set method
    public String name;

    public String getName() {
        return name;

    public void setName(String name) { = name;

Test class

public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = context.getBean("user", User.class);
@Autowired: auto assembly type, name. If autowritten cannot uniquely auto assemble attributes, you need to pass @ qualifier (value = "XXX")
@Nullable: the field is marked with this annotation, indicating that the field can be null
@Resource: automatic assembly, by name, and then by type
@Component: component, placed in type, indicates that this class is managed by spring, that is, bean. The following is the derived annotation of component. In web development, we will layer according to MVC three-tier architecture!
Controller: @ controller these four annotations have the same function. They all represent registering a class in spring and assembling beans


XML and annotations:

  • XML is more versatile and suitable for any occasion! Simple and convenient maintenance
  • Note: not their own classes can’t be used, and maintenance is relatively complex

Best practices for XML and annotations:

  • XML is used to manage beans
  • Annotations are only responsible for completing attribute injection
  • In the process of using, we only need to pay attention to one problem. If we must make the annotation effective, we need to turn on the annotation support
<!-- Specify the package to be scanned, and the annotations under the package will take effect -- >
<context:component-scan base-package="com.hudu"/>

This work adoptsCC agreement, reprint must indicate the author and the link to this article