Spring注解开发:

通过采用注解的方式进行开发,替代原先在xml中的配置文件标签。

1.Spring原始注解:

Spring原始注解主要是替代< Bean >标签的配置

给出图总

7U55M8.png

具体介绍

1.@Component可以在web,service,dao层三层上实例化bean,后跟参数为bean中的id。

1
@Component("UserDao")

但为了增加可读性,即能很好的观察当前注解的哪一层,采用@Repository注解用于dao层,@Service注解御用service层,采用@Controller注解用于web层。

1
2
3
@Repository("UserDao")      //dao层注解,放在userDao实现类上方
@Service("UserService") //service层注解,放在service实现类上方
@Controller("UserController") //web层注解,放在web实现类上方

2.@Autowired替代依赖注入的标签,可以省去set方法或者有参构造方法,该注解类似于bean的第二种接收数据类型的,即参数为数据类型,如果该数据类型只有一个可以使用,多个不可使用。

@Qualifier在上面注解的基础上参数为id,类似于bean的第一种,可以根据id进行依赖注入。

​ 如果要根据id注入,两个注解都要写。

@Resource表示上述两个的组合。

7U5fRP.png

3.@Value按值注入,可以注入基本数据类型,但不常用,多数用于使用spel表达式接收参数,然后注入。

@Scope表示范围,与bean中的scope属性一样。

2.Spring新注解:

使用上面的原始注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:

  • 非自定义的Bean的配置: < bean >

  • 加载properties文件的配置:< context:property-placeholder >

  • 组件扫描的配置:< context:component-scan >

  • 引入其他文件:< import >

7U5hxf.png

具体操作

首先创建一个SpringConfig包,在里面实现注解类SpringConfiguration,用来替代applicationContext.xml。

接下来分别替代以上文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//标志该类是Spring的核心配置类
@Configuration

//<context:component-scan base-package = "spring"/> //扫描标签
@ComponentScan("spring") //扫描注解,用于扫描所有spring包下的注解。

//<context:property-palceholder location = "classpath:jdbc.properties"/> 加载配置文件标签
@PropertySource("classpath:jdbc.properties") //加载配置文件注解。

bean标签(第三方类)的注解使用@Bean("dataSource") //Spring会将当前方法的返回值以指定名称存储到Spring容器中。
在该注解下编写该类实现代码,并通过Value使用spel表达式获取值后传参。

//<import resource = "1.class" />
@import({1.class,2.class.......}) //参数为一个数组,里面包含多个子配置类。

添加Spring配置类后,需要修改生成Spring工厂的方式:

1
2
3
4
5
ApplicationContext app = new ClssPathXmlApplicationContext("applictaionContext.xml");
//xml标签配置时的spring加载方式。

ApplicationContext app = new AnnotationConfigApplicationContext("SpringConfiguration.class");
//采用注解开发后的spring加载方式。

接下来给出三种Spring相关API:

ApplicationContext的实现类:

  • ClssPathXmlApplicationContext 从类的根路径下加载配置文件

  • FileSystemXmlApplicationContext 从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。

  • AnnotationConfigApplicationContext 当使用注解配置容器对象时,下需要使用此类来创建Spring容器,它用来读取注解。