Spring Maven 项目建立好了
这个是项目目录
先把上面的三个包建好然后把这4个 .java文件和一个HellWorld接口建好。
然后在src/main/resources建beans.xml文件
以下是每个重要的文件的项目代码:
package com.impl;
import com.xynet.HelloWorld;
public class SpringHelloWorld implements HelloWorld {
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("Spring测试成功!!");
}
}
package com.impl;
import com.xynet.HelloWorld;
public class StrutsHelloWorld implements HelloWorld{
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("Struts测试成功!!");
}
}
package com.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.xynet.HelloWorld;
import com.xynet.HelloWorldService;
public class HelloProgram {
public static void main(String[] args) {
ApplicationContext context=
new ClassPathXmlApplicationContext("beans.xml");
HelloWorldService service=
(HelloWorldService) context.getBean("helloWorldService");
HelloWorld hw=service.getHelloWorld();
hw.sayHello();
HelloWorldService service2=
(HelloWorldService) context.getBean("helloWorldService2");
HelloWorld hw2=service2.getHelloWorld();
hw2.sayHello();
}
}
package com.xynet;
public interface HelloWorld {
public void sayHello();
}
package com.xynet;
public class HelloWorldService {
private HelloWorld helloWorld;
public HelloWorldService(){
}
public void setHelloWorld(HelloWorld helloWorld){
this.helloWorld=helloWorld;
}
public HelloWorld getHelloWorld() {
return this.helloWorld;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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="springHelloWorld"
class="com.impl.SpringHelloWorld"></bean>
<bean id="strutsHelloWorld"
class="com.impl.StrutsHelloWorld"></bean>
<bean id="helloWorldService"
class="com.xynet.HelloWorldService">
<property name="helloWorld" ref="springHelloWorld"/>
</bean>
<bean id="helloWorldService2"
class="com.xynet.HelloWorldService">
<property name="helloWorld" ref="strutsHelloWorld"/>
</bean>
</beans>
测试成功!
我做的时候大概用了一天时间才做出来 一般时间用在了把 Maven和Spring添加到Ecplise中这俩都配置好了之后,然后把我的项目目录建好,然后分别把代码放进去。应该就没问题了。第一个Spring项目。如果运行报错什么的不要慌,多试几次总会成功的,Spring都是前人总结好的经验,只要细心就没问题。
(关注我互粉,互相学习)