spring5 入门(四)使用注解开发

时间:2021-09-03
本文章向大家介绍spring5 入门(四)使用注解开发,主要包括spring5 入门(四)使用注解开发使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

首先使用注解开发,必须在xml中导入context约束,下列代码红色部分,

<?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
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd

</beans>

之前我们都是在xml中同过bean注册一个类,现在可以直接通过@Component通过这个注解,进行注册,代码如下:

@Component
public class Teacher {

    @Value("xxxxx")
    private String name;
    @Autowired
    private Student student;

    public Teacher() {

    }

其中可以通过@Value这个注解进行变量值的注入,整个操作代替了bean注册的操作,当使用@Component注解的类要被xml文件扫描到,需要配置对应扫描路径

之所以要这样配,是因为我们的上下文对象是,是通过xml文件这个resource源有参构造出来的,对应扫描配置如下:

    <context:component-scan base-package="com.hys.pojo"/>

XML与注解比较

  • XML可以适用任何场景 ,结构清晰,维护方便

  • 注解不是自己提供的类使用不了,开发简单方便

xml与注解整合开发 :推荐最佳实践

  • xml管理Bean

  • 注解完成属性注入

  • 使用过程中, 可以不用扫描,扫描是为了类上的注解

基于java类进行配置,上面所述的上下文对象除了使用源文件,可以通过java配置类构建出来:

一个是基于java配置类

一个是基于xml文件

  ApplicationContext context = new AnnotationConfigApplicationContext(studengconfig.class);
  ApplicationContext context2 = new ClassPathXmlApplicationContext("bean.xml");

基于java配置类,完全可以省去了xml配置文件,在spring-boot中基本都是这样的!代码如下:

@Configurable代表了这个类表示为对应bean.xml文件

@Bean即文件中的bean属性 ,该方法的返回值类型,代表对应类,方法名代表对应id

@ComponentScan("com.hys.pojo") 表示扫描使用了@Component的类,进行bean注册

@Configurable
@ComponentScan("com.hys.pojo")
public class studengconfig {
    @Bean
    public Student student(){
        return new Student();
    }
}

原文地址:https://www.cnblogs.com/carry-huang/p/15222191.html