HelloSpring
下边通过一个简单的HelloSpring程序来感受Spring框架的优点吧!
Spring整合POJO层的数据
步骤:
搭建完整的pojo层
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21package com.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}在resource中创建一个
beans.xml
文件配置文件中的格式可以在官方文档中找到
1
2
3
4
5
6
7
8
9
<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">
</beans>将pojo包下的类整合到配置文件中
使用
<properties/>
来给实体类中的参数赋值1
<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="hello" class="com.pojo.Hello"> <property name="str" value="Spring"/> </bean></beans>
编写测试类
测试类
此时的测试类在调用pojo成时,就不用再去实例化对象,只需要调用Spring容器即可
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
使用这个context中的getBean("bean的id")
这个方法就能调用到一个对象
理论分析
1 | <bean id="hello" class="com.pojo.Hello"> |
- 这里的
<bean></bean>
就可以视为是对对象实例化的过程 id
代表这个对象的名字class
代表这个对象的类<properties/>
这里表示赋值的过程name
表示参数的名字,value
表示付给参数的值
Spring整合Dao层
编写Dao抽象类以及他的实体类
对实体类进行整合(也是在beans.xml中进行整合的)
1
2<bean id="MyBtais" class="dao.MybatisUserDaoImp"/>
<bean id="User" class="dao.UserDaoImp"/>
Spring整合Service层
编写Service层的抽象类以及他的所有的实现类
对实体类进行整合(bean.xml中)
由于我们那个IOC思想是service可以调用多个Dao,因此这里使用注册好的Dao
1
2
3
4
5
6
7
8
9<!--注册好和Dao-->
<bean id="MyBtais" class="dao.MybatisUserDaoImp"/>
<bean id="User" class="dao.UserDaoImp"/>
<!--因为我们为了满足IOC原则 对userDao进行赋值-->
<!--此处使用ref 而不是 value value表示一个值-->
<!--而此时我们的ref表示已经注册过得bean的id-->
<bean id="UserService" class="service.UserServiceImp">
<property name="userDao" ref="MyBtais"/>
</bean>编写测试类
同理只要是通过Spring整合的,只用Spring的容器就能解决变量实例化的过程
1 | public static void main(String[] args) { |
需要注意的是,我们这里有一个很明显的强制转型,如果没有转型,系统默认得到的userService是object类型,这样我们就不能调用想要的方法了
注意手动去进行强转
这样,我们的代码就再也不用改变了,只需要用户改变配置文件即可
Donate