登录/注册
唐某
11055
占位
7
占位
31
浏览量
占位
粉丝
占位
关注
Spring 注解配置的基本要素
唐某
2021-01-12 10:42:38 2021-01-12
353
0

Spring 注解配置的基本要素

随着Spring的流行,我们经历过基于XML-Based 的配置,随着SpringBoot的流行,我们逐渐使用基于注解的配置替换掉了基于XML-Based的配置,那么你知道基于注解的配置的基础组件都是什么吗?都包括哪些要素?那么本节就来探讨一下。注:本篇文章更多的是讨论Spring基于注解的配置一览,具体的技术可能没有那么深,请各位大佬见谅。

探讨主题:

  • 基础概念:@Bean 和 @Configuration
  • 使用AnnotationConfigApplicationContext 实例化Spring容器
  • 使用@Bean 注解
  • 使用@Configuration 注解
  • 编写基于Java的配置
  • Bean定义配置文件
  • PropertySource 抽象类
  • 使用@PropertySource
  • 占位符的声明

基础概念:@Bean 和 @Configuration

Spring中新的概念是支持@Bean注解 和 @Configuration 注解的类。@Bean 注解用来表明一个方法实例化,配置并且通过IOC容器初始化并管理一个新的对象。@Bean注解就等同于XML-Based中的<beans/>标签,并且扮演了相同的作用。你可以使用基于注解的配置@Bean 和 @Component,然而他们都用在@Configuration配置类中。

使用@Configuration 注解的主要作用是作为bean定义的类,进一步来说,@Configuration注解的类允许通过调用同类中的其他@Bean标注的方法来定义bean之间依赖关系。 如下所示:

新建一个maven项目(我一般都直接创建SpringBoot项目,比较省事),创建AppConfig,MyService,MyServiceImpl类,代码如下:

@Configuration
public class AppConfig {
@Bean
public MyService myService(){
return new MyServiceImpl();
}
}
public interface MyService {}
public class MyServiceImpl implements MyService {}

上述的依赖关系等同于XML-Based:

<beans>
<bean id="myService",class="com.spring.annotation.service.impl.MyServiceImpl"/>
</beans>

使用AnnotationConfigApplicationContext 实例化Spring容器

AnnotationConfigApplicationContext 基于注解的上下文是Spring3.0 新添加的注解,它是ApplicationContext的一个具体实现,它可以接收@Configuration注解的类作为输入参数,还能接收使用JSR-330元注解的普通@Component类。

当提供了@Configuration 类作为输入参数时,@Configuration类就会注册作为bean的定义信息并且所有声明@Bean的方法也都会作为bean的定义信息。

当提供@Component和JSR-330 声明的类时,他们都会注册作为bean的定义信息,并且假设在必要时在这些类中使用诸如@Autowired或@Inject之类的注解

简单的构造

在某些基于XML-Based的配置,我们想获取上下文容器使用ClassPathXmlApplicationContext,现在你能够使用@Configuration 类来实例化AnnotationConfigApplicationContext。

MyService中添加一个printMessage()方法,实现类实现对应的方法。新建测试类进行测试

public class ApplicationTests {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyService service = context.getBean(MyService.class);
// printMessage() 输出something...
service.printMessage();
}
}

如前所述,AnnotationConfigApplicationContext不仅限于使用@Configuration类。 任何@Component或JSR-330带注释的类都可以作为输入提供给构造函数,如下例所示

public class ApplicationTests {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MyServiceImpl.class,Dependency1.class,Dependency2.class);
MyService myService = context.getBean(MyService.class);
myService.printMessage();
}
}

使用register注册IOC容器

你可以实例化AnnotationConfigApplicationContext通过使用无参数的构造器并且使用register方法进行注册,它和AnnotationConfigApplicationContext带参数的构造器起到的效果相同。

```java

public class ApplicationTests {

public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class, OtherConfig.class);
ctx.register(AdditionalConfig.class);
ctx.refresh();
MyService my
暂无评论