Spring有很多优点:轻量级,非侵入性,面向切面,容器,框架
我们是用spring核心包之BeanFactory构造最经典的helloWorld
接口隔离开来
package HelloWorld;

public interface GreetingHelloworld ...{
public void sayHelloworld();
}



实现类:
使用spring的IOC依赖注入机制,两种方式:设值注入(成员变量)和构造注入(构造函数参数)
package HelloWorld;

public class GreetingHelloworldImpl implements GreetingHelloworld ...{
private String greetingText;
private String greetingFromConstructor;
public GreetingHelloworldImpl(String greetingFromConstructor)...{
this.greetingFromConstructor=greetingFromConstructor;
}
public GreetingHelloworldImpl()...{
}
public String getGreetingText() ...{
return greetingText;
}
public void setGreetingText(String greetingText) ...{
this.greetingText = greetingText;
}
public void sayHelloworld() ...{
System.out.println(this.getGreetingText());
System.out.println(this.getGreetingFromConstructor());
}
public String getGreetingFromConstructor() ...{
return greetingFromConstructor;
}
public void setGreetingFromConstructor(String greetingFromConstructor) ...{
this.greetingFromConstructor = greetingFromConstructor;
}
}
spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
<beans>
<bean id="greeting" class="HelloWorld.GreetingHelloworldImpl">
<constructor-arg>
<value>this is helloworld from construtor</value>
</constructor-arg>
<property name="greetingText">
<value>hello world!</value>
</property>
</bean>
</beans>
测试用例:
package HelloWorld;
import java.io.File;
import java.net.URISyntaxException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;



public class TestHelloWorld ...{

public static void main(String[] args) ...{
String filePath=System.getProperty("user.dir")+File.separator+"HelloWorld"+File.separator+"hello.xml";
BeanFactory factory=new XmlBeanFactory(new FileSystemResource(filePath));
GreetingHelloworldImpl greetingSerview=(GreetingHelloworldImpl)factory.getBean("greeting");
greetingSerview.sayHelloworld();
}
// public static String getRealPath(String filename){
// String path="";
// Class theClass=TestHelloWorld.class;
// java.net.URL u= theClass.getResource(filename);
// return u.getPath();
//
//
// }


}
运行结果:
hello world!
this is helloworld from construtor
本文介绍了一个使用Spring框架的经典Hello World示例,展示了如何通过Spring的BeanFactory进行依赖注入,并使用接口和实现类来构建应用程序。
724

被折叠的 条评论
为什么被折叠?



