从Spring 3开始, JavaConfig功能已包含在核心Spring模块中,它使开发人员可以将bean定义和Spring配置从XML文件移到Java类中。
但是,您仍然可以使用经典的XML方式定义bean和配置, JavaConfig只是另一种替代解决方案。
看到经典XML定义和JavaConfig在Spring容器中定义bean的区别。
Spring XML文件:
<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.mkyong.hello.impl.HelloWorldImpl">
</beans>
JavaConfig中的等效配置:
package com.mkyong.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.mkyong.hello.HelloWorld;
import com.mkyong.hello.impl.HelloWorldImpl;
@Configuration
public class AppConfig {
@Bean(name="helloBean")
public HelloWorld helloWorld() {
return new HelloWorldImpl();
}
}
Spring JavaConfig Hello World
现在,查看完整的Spring JavaConfig示例。
1.目录结构
请参阅本示例的目录结构。
2.依赖库
要使用JavaConfig( @Configuration ),您需要包括CGLIB库。 查看依赖关系:
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- JavaConfig need this library -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
3.Spring Bean
一个简单的豆。
package com.mkyong.hello;
public interface HelloWorld {
void printHelloWorld(String msg);
}
package com.mkyong.hello.impl;
import com.mkyong.hello.HelloWorld;
public class HelloWorldImpl implements HelloWorld {
@Override
public void printHelloWorld(String msg) {
System.out.println("Hello : " + msg);
}
}
4. JavaConfig注释
用@Configuration
注释以告诉Spring这是Spring的核心配置文件,并通过@Bean
定义bean。
package com.mkyong.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.mkyong.hello.HelloWorld;
import com.mkyong.hello.impl.HelloWorldImpl;
@Configuration
public class AppConfig {
@Bean(name="helloBean")
public HelloWorld helloWorld() {
return new HelloWorldImpl();
}
}
5.运行
使用AnnotationConfigApplicationContext
加载JavaConfig类。
package com.mkyong.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.mkyong.config.AppConfig;
import com.mkyong.hello.HelloWorld;
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
HelloWorld obj = (HelloWorld) context.getBean("helloBean");
obj.printHelloWorld("Spring3 Java Config");
}
}
输出量
Hello : Spring3 Java Config
下载源代码
下载它– Spring3-JavaConfig-Example.zip (6 KB)
参考
标签: javaconfig spring3
翻译自: https://mkyong.com/spring3/spring-3-javaconfig-example/