Spring 专题
专题目录
您的位置:java > Spring专题 > Spring JavaConfig实例
Spring JavaConfig实例
作者:--    发布时间:2019-11-20
从spring 3起,javaconfig功能已经包含在spring核心模块,它允许开发者将bean定义和在spring配置xml文件到java类中。
但是,仍然允许使用经典的xml方式来定义bean和配置,javaconfig是另一种替代解决方案。
看来看经典的xml定义和javaconfig的不同,如下定义在spring容器中的bean。

spring xml file - applicationcontext.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.h3.hello.impl.helloworldimpl">
		
</beans>
等效于以下javaconfig的配置:
package com.h3.config;

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import com.h3.hello.helloworld;
import com.h3.hello.impl.helloworldimpl;

@configuration
public class appconfig {
	
    @bean(name="hellobean")
    public helloworld helloworld() {
        return new helloworldimpl();
    }
	
}

spring javaconfig hello world

现在,看到一个完整的spring javaconfig例子。

1. 工程目录结构

这个例子的目录结构如下。

3. spring bean

一个简单的bean

package com.h3.hello;
 
public interface helloworld {
	
	void printhelloworld(string msg);
 
}
package com.h3.hello.impl;

import com.h3.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.h3.config;

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import com.h3.hello.helloworld;
import com.h3.hello.impl.helloworldimpl;

@configuration
public class appconfig {
	
    @bean(name="hellobean")
    public helloworld helloworld() {
        return new helloworldimpl();
    }
	
}

5. 执行结果

使用 annotationconfigapplicationcontext 加载您的javaconfig类

package com.h3.core;
 
import org.springframework.context.applicationcontext;
import org.springframework.context.annotation.annotationconfigapplicationcontext;
import com.h3.config.appconfig;
import com.h3.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("spring java config");

	}
}

输出结果

hello : spring java config


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册