(7) Spring from entry to soil-using annotations

Use annotation development

Description

After spring 4, if you want to use the annotation form, you must introduce the aop package

image

In the configuration file, you have to introduce a context constraint

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

</beans>

Implementation of Bean

We used bean tags for bean injection before, but in actual development, we generally use annotations!

1. Configure the annotations under which packages to scan

<!--指定注解扫描包-->
<context:component-scan base-package="com.zhonghu.pojo"/>

2. Write the class under the specified package and add annotations

@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
   public String name = "冢狐";

}

3. Test

@Test
public void test(){
   ApplicationContext applicationContext =
       new ClassPathXmlApplicationContext("beans.xml");
   User user = (User) applicationContext.getBean("user");
   System.out.println(user.name);
}

Attribute injection

Use annotations to inject properties

1. You can add @value("value") directly to the direct name without providing the set method

@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
   @Value("冢狐")
   // 相当于配置文件中 <property name="name" value="冢狐"/>
   public String name;
}

2. If the set method is provided, add @value("value") to the set method;

@Component("user")
public class User {

   public String name;

   @Value("冢狐")
   public void setName(String name) {
       this.name = name;
  }
}

Derivative annotation

Our annotations replace the configuration steps in the configuration file! More convenient and faster!

@Component three derivative annotations

In order to better layer, Spring can use the other three annotations, which have the same function, and which function is currently used are the same.

  • @Controller: web layer
  • @Service: service layer
  • @Repository: dao layers

Writing these annotations is equivalent to handing over this class to Spring to manage the assembly!

Automatic assembly annotation

  • @Autowired: Automatic assembly passed the type, find the name again if you can't find it

    • If it can’t uniquely automatically assemble the attributes, you need to pass @Qualifier(value="xxx")
  • @Nullable: This annotation is automatically marked, indicating that this annotation can be null

  • @Resource: auto-assembly passed the name, no retype was found

Scope

@scope

  • singleton: By default, Spring will create this object in a singleton mode. Close the factory and all objects will be destroyed.
  • Prototype: Multi-example mode. Close the factory, all objects will not be destroyed. The internal garbage collection mechanism will recycle
@Controller("user")
@Scope("prototype")
public class User {
   @Value("冢狐")
   public String name;
}

summary

Comparison of XML and annotations

  • XML can be applied to any scene, with clear structure and easy maintenance
  • The annotations are not self-provided classes and cannot be used, the development is simple and convenient, and the maintenance is difficult

xml and annotation integration development : recommended best practices

  • xml management bean
  • Annotation completes attribute injection
  • During use, you don’t need to scan. Scanning is for annotations on the class.
<context:annotation-config/>

effect:

  • Carry out annotation-driven registration to make annotations take effect
  • Used to activate the annotations on the beans that have been registered in the spring container, that is, to register with Spring
  • If you do not scan the package, you need to manually configure the bean
  • If you do not add annotation-driven, the injected value is null!

Configure based on Java classes

​ We now have to completely not use Spring's xml configuration, and leave it to java to handle it.

​ JavaConfig was originally a sub-project of Spring. It provides Bean definition information in the form of Java classes. In the version of Spring4, JavaConfig has officially become the core function of Spring4.

image

1. Write an entity class, User

// 此注解表明一个类作为组件类,并告知Spring要为这个类创建bean
@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }
    @Value("冢狐")
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

2. Create a new config configuration package and write a MyConfig configuration class

// 这个也会Spring容器托管,注册到容器中,因为它本身就是一个@Conmponent
// @Configuration代表这是一个配置类,和我们之前看到的beans.xml是一样的
@Configuration
@ComponentScan("com.zhonghu.pojo")
public class MyConfig {
    // 注册一个bean,就相当于我们之前写的一个bean标签
    // 这个方法的名字,相当于我们bean标签中的id
    // 这个方法的返回值,相当于我们bean标签中的class属性
    @Bean
    public User getUser(){
        // 就是返回要注入的bean的对象
        return new User();
    }
}

3. Test

public class MyTest {
    public static void main(String[] args) {
        // 如果我们完成使用了配置类方式去实现,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class来加载对象
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User getUser = (User) context.getBean("getUser");
        System.out.println(getUser.getName());
    }
}

4. Output the result successfully!

How to import other configurations?

1. Let's write another configuration class!

@Configuration  //代表这是一个配置类
public class MyConfig2 {
}

2. In the previous configuration class, let's choose to import this configuration class

@Configuration
@Import(MyConfig2.class)  //导入合并其他配置类,类似于配置文件中的 inculde 标签
public class MyConfig {

   @Bean
    public User getUser(){
        // 就是返回要注入的bean的对象
        return new User();
    }

}

At last

  • If you feel that you are rewarded after reading it, I hope to give me a thumbs up. This will be the biggest motivation for me to update. Thank you for your support.
  • Welcome everyone to pay attention to my public account [Java Fox], focusing on the basic knowledge of java and computer, I promise to let you get something after reading it, if you don’t believe me, hit me
  • If you have different opinions or suggestions after reading, please comment and share with us. Thank you for your support and love.

image

Welcome to follow the public account "Java Fox" for the latest news

Guess you like

Origin blog.csdn.net/issunmingzhi/article/details/112424479