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>
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();
}
}
一个简单的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);
}
}
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();
}
}
使用 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