Spring(八)之基於Java配置

來源:互聯網
上載者:User

標籤:this   strong   new   pack   基於   解釋   org   tutorial   beans   

基於 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.*;@Configurationpublic 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();       }}

 

運行結果如下:

 

Spring(八)之基於Java配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.