发表于: 2017-03-07 17:09:12
1 1472
明天的计划:完成任务1.22---1.24
学习Spring:
定义一个 Spring 管理容器中的 Bean :
public class PersonService {
private String name;
public void setName(String name) {
this.name = name;
}
public void info() {
System.out.println("人名为:" + name);
}
}
主程序,该程序初始化 Spring 容器:
public class SpringTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
System.out.println(ctx);
PersonService p = ctx.getBean("personService", PersonService.class);
p.info();
}
}
Spring 配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="personService" class="hsl.service.PersonService">
<property name="name" value="niu"/>
</bean>
</beans>
运行结果:
练习调试:
遇到的问题:
出现错误:class path resource [bean.xml] cannot be opened because it does not exist
解决方法:将bean.xml放到scr根目录,或者使用时加上bean.xml的路径。
评论