Spring - 基于Java配置的注解

22 篇文章 0 订阅

如果你已经很好使用XML的配置文件的方式实现依赖注入,那么没有那么必要再去学习如果使用基于Java配置的方式实现依赖注入,因为两者是相同的作用。

使用Java配置的方式可以让你在没有XML配置文件的方式下实现依赖注入,这章我们将简单介绍。

@Configuration & @Bean Annotations

使用@Configuration的类表明这个类可以被IoC容器使用,并指明相关bean的定义。@Bean注解的方法是告诉Spring容器,这个方法将返回一个对象,并且这个对象应该在Spring application context中被注册成一bean。

简单的@Configuration类如下所示:

package com.soygrow;
import org.springframework.context.annotation.*;

@Configuration
public class HelloWorldConfig {
   @Bean 
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}

以上是一个Java的配置类,相当于XML中下面配置:

<beans>
    <bean id = "helloWorld" class = "com.soygrow.HelloWorld" />
<beans>

用@Bean注解的方法名可以作为一个bean Id来工作,该方法将创建并返回实际的bean。当然,你的配置类可以有多个@Bean的声明。一旦你的配置类被定义,你就可以使用AnnotationConfigApplicationContext加载病提供给Spring 容器使用。比如:

public static void main(String[] args) {
   ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);

   HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
   helloWorld.setMessage("Hello World!");
   helloWorld.getMessage();
}

你也可以像下面这样加载多个配置类:

public static void main(String[] args) {
   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

   ctx.register(AppConfig.class, OtherConfig.class);
   ctx.register(AdditionalConfig.class);
   ctx.refresh();

   MyService myService = ctx.getBean(MyService.class);
   myService.doStuff();
}

Example

HelloWorld.java

package com.soygrow.JavaConfig;

public class HelloWorld {
    private String message;

    public void getMessage() {
        System.out.println("Your Message : " + message);
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

HelloWorldConfig.java

package com.soygrow.JavaConfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HelloWorldConfig {
    @Bean
    public HelloWorld helloWorld() {
        return new HelloWorld();
    }
}

MainApp.java

package com.soygrow.JavaConfig;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);

        HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
        helloWorld.setMessage("Hello World Java Config!");
        helloWorld.getMessage();
    }
}

如果一切正常,那么运行结果是:

Your Message : Hello World Java Config!

代码说明
- @Bean声明一个被Spring 容器使用的bean
- 使用对应的方式加载Java配置的方式

Injecting Bean Dependencies

当@Bean注解的bean依赖另外一个注解的bean时,这种方式相同的,如下所示:

package com.tutorialspoint;
import org.springframework.context.annotation.*;

@Configuration
public class AppConfig {
   @Bean
   public Foo foo() {
      return new Foo(bar());
   }
   @Bean
   public Bar bar() {
      return new Bar();
   }
}

这里foo bean需要一个bar实例的引用的构造注入,下面让我们看另外一个例子。

Example

TextEditor.java

package com.soygrow.JavaConfig;

public class TextEditor {
    private SpellChecker spellChecker;

    public TextEditor(SpellChecker spellChecker){
        System.out.println("Inside TextEditor constructor." );
        this.spellChecker = spellChecker;
    }
    public void spellCheck(){
        spellChecker.checkSpelling();
    }
}

SpellChecker.java

package com.soygrow.JavaConfig;

public class SpellChecker {
    public SpellChecker(){
        System.out.println("Inside SpellChecker constructor." );
    }
    public void checkSpelling(){
        System.out.println("Inside checkSpelling." );
    }
}

TextEditorConfig.java

package com.soygrow.JavaConfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TextEditorConfig {
    @Bean
    public TextEditor textEditor() {
        return new TextEditor(spellChecker());
    }

    @Bean
    public SpellChecker spellChecker() {
        return new SpellChecker();
    }
}

MainApp.java

package com.soygrow.JavaConfig;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApp {
    public static void main(String[] args) {
        test2();
    }

    public static void test2() {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(TextEditorConfig.class);
        TextEditor te = ctx.getBean(TextEditor.class);
        te.spellCheck();
    }
}

The @Import Annotation

@Import注解可以允许从其他配置类中加载@Bean的定义。如下所示:

@Configuration
public class ConfigA {
   @Bean
   public A a() {
      return new A(); 
   }
}
@Configuration
@Import(ConfigA.class)
public class ConfigB {
   @Bean
   public B a() {
      return new A(); 
   }
}

现在你可以使用ConfigB需要按照下面这样定义:

public static void main(String[] args) {
   ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);

   // now both beans A and B will be available...
   A a = ctx.getBean(A.class);
   B b = ctx.getBean(B.class);
}

Lifecycle Callbacks

使用@Bean支持指定任意的初始化和销毁的回调方法,和XML中的init-methoddestroy-method一样:

public class Foo {
   public void init() {
      // initialization logic
   }
   public void cleanup() {
      // destruction logic
   }
}
@Configuration
public class AppConfig {
   @Bean(initMethod = "init", destroyMethod = "cleanup" )
   public Foo foo() {
      return new Foo();
   }
}

Specifying Bean Scope

和XML一样默认的scope是单例(Singleton),但是你可以像下面这样使用@Scope注解:

@Configuration
public class AppConfig {
   @Bean
   @Scope("prototype")
   public Foo foo() {
      return new Foo();
   }
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值