標籤: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配置