Spring学习(一)
作者:互联网
Spring体系结构
- bean,core,context,SpEL
Spring开发步骤
业务层(service)
DAO层(DAO)
- 导入Spring基本包
- 编写DAO接口和Impl类
- 创建Spring核心配置文件
- 在Spring配置文件中配置Impl
- 使用SpringAPI获取Bean实例
例子
public interface UserDAO {
public void save();
}
public class UserDaoImpl implements UserDAO {
@Override
public void save() {
System.out.println("save running");
}
}
///
<?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.xsd">
<bean id="userDao" class = "zk.dao.impl.UserDaoImpl"></bean>
</beans>
///
package zk.demo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import zk.dao.UserDAO;
public class UserDemo {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDAO dao = (UserDAO) app.getBean("userDao");
dao.save();
}
}
Bean标签范围配置
scope
- singleton 单例的,默认值。加载配置文件时创建
- prototype 多例的,getBean的时候创建
- request
- session
- global session
生命周期的配置
- init-method
- destropy-method
Bean实例化方式
- 无参构造 class = "包.类"
- 工厂静态 class = "包.工厂" factory-method="工厂.静态方法"
- 工厂实例 现配一个工厂bean,再配一个类bean
Bean依赖注入
把业务层和持久层的依赖关系交给Spring去管理
-
set方法注入
<property name="" ref=""></property>
-
简单的set方法,加个p命名空间
<bean id="" class="" p:userDao-ref="userDao"></bean>constructor-arg
-
有参构造
<property constructor-arg="" ref=""></property>
普通数据注入
<bean id="userDao" class = "zk.dao.impl.UserDaoImpl">
<property name="name" value="zhangsan"></property>
<property name="age" value="1"></property>
</bean>
集合注入
<bean id="userDao" class = "zk.dao.impl.UserDaoImpl">
<property name="strList">
<list>
<value>aaa</value>
<value>bbb</value>
<value>ccc</value>
</list>
</property>
<property name="stringUserMap">
<map>
<entry key="user1" value-ref="user1"/>
<entry key="user2" value-ref="user2"/>
</map>
</property>
<property name="properties">
<props>
<prop key="p1">ppp1</prop>
<prop key="p2">ppp2</prop>
<prop key="p3">ppp3</prop>
</props>
</property>
</bean>
引入其他模块
<import resource="applicationContext-user.xml"/>
<import resource="applicationContext-product.xml"/>
标签:UserDAO,Spring,class,学习,Bean,save,public 来源: https://www.cnblogs.com/destinyzk/p/16663127.html