Spring(八)之基于Java配置

基于 Java 的配置

到目前为止,你已经看到如何使用 XML 配置文件来配置 Spring bean。如果你熟悉使用 XML 配置,那么我会说,不需要再学习如何进行基于 Java 的配置是,因为你要达到相同的结果,可以使用其他可用的配置。

基于 Java 的配置选项,可以使你在不用配置 XML 的情况下编写大多数的 Spring,但是一些有帮助的基于 Java 的注解,解释如下:

@Configuration 和 @Bean 注解

带有 @Configuration 的注解类表示这个类可以使用 Spring IoC 容器作为 bean 定义的来源。@Bean 注解告诉 Spring,一个带有 @Bean 的注解方法将返回一个对象,该对象应该被注册为在 Spring 应用程序上下文中的 bean。

演示示例:

(1).编写HelloWorldConfig.java

package com.tutorialspoint;
import org.springframework.context.annotation.*;
@Configuration
public class HelloWorldConfig {
   @Bean 
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}

上面代码相当于

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

(2)编写HelloWorld.java

package com.tutorialspoint;

public class HelloWorld {
   private String message;

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

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

(3)编写MainApp.java

package com.tutorialspoint;
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!");
                  helloWorld.getMessage();
       }
}

运行结果如下:

猜你喜欢

转载自www.cnblogs.com/youcong/p/9460307.html