1. 空构造器实例化:
2. 有参数构造器实例化:
public interface HelloWorld {
public void sayHello();
}
接下来为这个接口创建一个实现类HelloWorldImpl:
public class HelloWorldImpl implements HelloWorld{
private String message;
/**
* 空构造器
*/
HelloWorldImpl(){
message="Hello World";
}
/**
* 带参数的构造器
* @param message
*/
HelloWorldImpl(String message){
this.message=message;
}
public void sayHello() {
System.out.println(message);
}
}
编写配置文件conf-instance.xml:
/**
* 使用无参数的构造函数来实例化bean
*/
public static void sayHelloWordWithNoArgs(){
BeanFactory factory=
new FileSystemXmlApplicationContext("src/conf/conf-instance.xml");
HelloWorld helloWorld=factory.getBean("helloWorldWithNoArgs",HelloWorldImpl.class);
helloWorld.sayHello();
}
/**
* 使用有参数的构造函数来实例化bean
*/
public static void sayHelloWorldWithArgs(){
BeanFactory factory=
new FileSystemXmlApplicationContext("src/conf/conf-instance.xml");
HelloWorld helloWorld=factory.getBean("helloWorldWithArgs",HelloWorldImpl.class);
helloWorld.sayHello();
}
public class HelloWorldStaticFactory {
/**
* 工厂方法
* @param message
* @return
*/
public static HelloWorld newInstance(String message){
//返回带参数的HelloWorldImpl构造的helloWorld实例
return new HelloWorldImpl(message);
}
}
接下来在配置文件中来配置当前bean
在Main中实例化Bean
public static void sayHelloWordStaticFactory(){
//读取配置文件,实例化一个IoC容器
BeanFactory factory=
new FileSystemXmlApplicationContext("src/conf/conf-instance.xml");
//从容器中获取bean,注意此处完全“面向接口编程而不是面向实现”
HelloWorld helloWorld=factory.getBean("helloWorldStaticFactory",HelloWorld.class);
//执行业务逻辑
helloWorld.sayHello();
}
public class HelloWorldInstanceFactory {
/**
* 工厂方法
* @param message
* @return
*/
public HelloWorld newInstance(String message){
//需要返回的bean实例
return new HelloWorldImpl(message);
}
}
在配置文件中配置相关属性:
public static void sayHelloWorldInstanceFactory(){
//读取配置文件,实例化一个IoC容器
BeanFactory factory=
new FileSystemXmlApplicationContext("src/conf/conf-instance.xml");
//从容器中获取bean,注意此处完全“面向接口编程而不是面向实现”
HelloWorld helloWorld=factory.getBean("helloWorldInstance",HelloWorld.class);
//执行业务逻辑
helloWorld.sayHello();
}