Spring之JavaConfig

Spring JavaConfig實例

從Spring 3起,JavaConfig功能已經包含在Spring核心模塊,它允許開發者將bean定義和在Spring配置XML文件到Java類中。但是,仍然允許使用經典的XML方式來定義bean和配置,JavaConfig是另一種替代解決方案。

我們寫一個簡單的實例看看,實現輸出 hello world

接口

package com.pepper.itf;

public interface HelloWorld {

	public void sayHello(String msg);

}

接口實現類

package com.pepper.impl;

import com.pepper.itf.HelloWorld;

public class HelloWorldImpl implements HelloWorld {

	@Override
	public void sayHello(String msg) {
		System.out.println(msg);
	}

}

JavaConfig類

package com.pepper.config;

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

import com.pepper.impl.HelloWorldImpl;
import com.pepper.itf.HelloWorld;

@Configuration
public class AppConfig {

	@Bean(name="helloBean")
	public HelloWorld helloWorld() {
		return new HelloWorldImpl();
	}
}

使用 AnnotationConfigApplicationContext 加載您的JavaConfig類

package com.pepper.main;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.pepper.config.AppConfig;
import com.pepper.itf.HelloWorld;

public class Test {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
		HelloWorld hello = (HelloWorld) context.getBean("helloBean");
		String msg = "This is Spring JavaConfig!";
		hello.sayHello(msg);
	}
}

運行程序,控制檯會輸出 : This is Spring JavaConfig!

注意,項目需要導入 spring-aop-5.1.3.RELEASE.jar 包

由此我們可以看出,JavaConfig類

package com.pepper.config;

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

import com.pepper.impl.HelloWorldImpl;
import com.pepper.itf.HelloWorld;

@Configuration
public class AppConfig {

	@Bean(name="helloBean")
	public HelloWorld helloWorld() {
		return new HelloWorldImpl();
	}
}

就類似於

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="helloBean" class="com.pepper.impl.HelloWorldImpl">

</beans>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章