spring自动装配 点我
spring-java装配 点我
本节目的:通过xml文件装配spring
整体目录:
下面是主要部分代码。
首先创建Interface:
package com.learn.spring.beanxml;
public interface HelloWorld {
public void sayhello();
}
spring实体类:
package com.learn.spring.beanxml;
public class SpringHelloWorld implements HelloWorld{
@Override
public void sayhello() {
System.out.println("hello spring !");
}
}
service层:
package com.learn.spring.beanxml;
public class HelloWorldService {
private HelloWorld helloWorld;
public HelloWorldService() {}
public HelloWorld getHelloWorld() {
return helloWorld;
}
public void setHelloWorld(HelloWorld helloWorld) {
this.helloWorld = helloWorld;
};
}
然后是主函数:
package com.learn.spring.beanxml;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorldTest {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
HelloWorldService service = (HelloWorldService) context.getBean("helloWorldService");
HelloWorld hw = service.getHelloWorld() ;
hw.sayhello();
}
}
然后书是beans.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.xsd">
<bean id="springHelloWorld"
class="com.learn.spring.beanxml.SpringHelloWorld"></bean>
<bean id="helloWorldService"
class="com.learn.spring.beanxml.HelloWorldService">
<property name="helloWorld" ref="springHelloWorld"/>
</bean>
</beans>
运行结果: