###解析外部配置文件
在resources文件夹下,新建db.properties(和数据库连接相关的信息)
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db
username=root
password=root
###开发步骤
1)创建maven工程
添加web.xml
添加tomcat运行环境
添加jar spring-webmvc,junit,commons-dbcp,mysql
添加application.xml
2)配置数据库的连接池信息
<!--
1.util:properties表示读取外部的属性文件,并实例化对象
2.id表示名称
3.location表示属性文件的位置
<util:properties id="dbConf" location="classpath:db.properties">
<!--配置数据库的连接池 1.使用spring表达式给属性赋值 2.spring表达式语法格式:#{ }--->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="#{dbConf.driverClassName}"/>
<property name="url" value="#{dbConf.url}"/>
<property name="username" value="#{dbConf.username}"/>
<property name="password" value="#{dbConf.password}"/>
</bean>
##基于注解的bean管理
##1.基于注解的方式实例化对象(推荐使用)
实例化对象和依赖注入有两种方式:配置文件,注解
1.扫描包 (配置文件)
<!--扫描包可以扫描当前包和子包下的所有类-->
<context:component-scan base-package="cn.tedu.dao">
2.特定功能(实例化功能)的注解
@Component通用注解:实例化对象
@Controller:实例化控制层类的对象
@Service:实例化业务层类的对象
@Reponsitory:实例化持久层类的对象
@Repository("userDao")
public class UserDaoImpl implements UserDao{
public void insertUser(){
System.out.println("添加成功!");
}
//在mybatis里,一般是定义一个接口,接口里面定义抽象方法,并在配置文件里面实现相应的抽象方法。
##2.生命周期管理
//@Component表示实例化对象
@Component
public class BeanLife {
public BeanLife(){
System.out.println("BeanLife");
}
//@PostConstruct表示定义初始化方法
//@PostConstruct:Tomcat运行环境依赖的jar包
@PostConstruct
public void init(){
System.out.println("init");
}
public void execute(){
System.out.println("execute");
}
//@PreDestroy表示定义销毁的方法
//@PreDestroy:Tomcat运行环境依赖的jar包
@PreDestroy
public void destroy(){
System.out.println("destroy");
}
}
##3.bean作用域
//通过注解实例化对象,默认为单例singleton
//@Scope定义bean的作用域
//@Scope("prototype")表示bean作用域为多例
@Component
@Scope("prototype")
public class DemoScope {
}
##4.延迟加载
//默认bean对象的实例化,是立即加载
//@Lazy设置bean是否延迟加载的注解
//@Lazy(true)设置bean对象为延迟加载
@Component
@Lazy(true)
public class DemoLazy {
public DemoLazy(){
System.out.println("DemoLazy");
}
}
#DI(动态地向某个对象提供它所要的对象)
参考:http://www.360doc.com/content/18/0125/09/27831725_724899826.shtml
##1.@Resource(推荐使用)
//1.@Resource tomcat运行环境依赖jar包中定义的注解
//2.@Resource 实现依赖注入
//3.@Resource 实现依赖注入,可以省略set方法
//4.@Resource默认依赖注入的方式为byName
//5.@Resource如果没有匹配的属性
// 按照byType方式实现依赖注入
//6.@Resource(name="userDaoImpl")
@Resource(name="userDaoImpl")
private UserDao userDao;
##2.@Autowired(了解)
public class UserServiceImpl2 implements UserService2{
//1.@Autowired 依赖注入
//2.@Autowired 默认依赖注入的方式byType;
// 如果有多个相同类型的对象,那么按照byName依赖注入
//3.如果使用byName实现依赖注入,
// 使用@Qualifier注解定义匹配的名称
//4.@Qualifier不能单独使用
@Autowired
@Qualifier("userDaoImpl")
private UserDao userDao;
public void addUser() {
userDao.insertUser();
}
}
##3.@Value(了解)
@Component
public class Student {
//@Value("Admin")给String或者基本数据类型依赖注入
//@Value("#{conf.name}")使用spring表达式实现依赖注入
@Value("#{conf.name}")
private String name;
public String toString(){
return "name="+name;
}
}
这篇博客概念性偏强,适合复习,不适合学习;