Spring
有很多接口.
与各层都有集成.
Spring的核心:
IOC(控制反转/依赖注入)
即自动new对象. 以及配置对象之间的关系
即对普通java对象增加功能.(声明式服务). 实例化a类时,a类中所依赖的元素也会通过setter和配置文件,通过spring自动new.
通过IOC容器来管理对象,以及他们的关系.
代码来源尚学堂:
小例子(不使用spring)
1.写一个UerDao接口
1package com.zyl.spring.dao;
2
3public interface UserDao {
4
5 public void save(String username,String password);
6
7 public void delete(String userid);
8
9 public void update(String username,String password);
10}
11 2.UserDao接口的两个实现
1package com.zyl.spring.dao;
2
3public class UserDao4Mysql implements UserDao {
4
5 @Override
6 public void delete(String userid) {
7 // TODO Auto-generated method stub
8
9 }
10
11 @Override
12 public void save(String username, String password) {
13 System.out.println("here is mysql");
14
15 }
16
17 @Override
18 public void update(String username, String password) {
19 // TODO Auto-generated method stub
20
21 }
22
23}
24
1package com.zyl.spring.dao;
2
3public class UserDao4Oracle implements UserDao {
4
5 @Override
6 public void delete(String userid) {
7 // TODO Auto-generated method stub
8
9 }
10
11 @Override
12 public void save(String username, String password) {
13 System.out.println("here is oracle");
14
15 }
16
17 @Override
18 public void update(String username, String password) {
19 // TODO Auto-generated method stub
20
21 }
22
23}
24 3.再来一个生产装配dao的工厂
1package com.zyl.spring.dao;
2
3public class UserDaoFactory {
4//工厂
5 private static UserDaoFactory instance=new UserDaoFactory();
6
7 private UserDaoFactory(){}
8
9 public static UserDaoFactory getInstance(){
10 return instance;
11 }
12
13 public UserDao createUseDao(){
14 return new UserDao4Mysql();
15 }
16} 4来个User管理类
1package com.zyl.spring.manager;
2
3import com.zyl.spring.dao.UserDao;
4import com.zyl.spring.dao.UserDaoFactory;
5
6public class UserManager {
7 private UserDao userdao;
8 //写一个单例
9 private static UserManager instance=new UserManager();
10 private UserManager(){
11 userdao= UserDaoFactory.getInstance().createUseDao();
12 } //构造方法
13
14
15
16 public static UserManager getInstace(){
17 return instance;
18 }
19 public void save(String username,String password){
20 userdao.save(username, password);
21 }
22
23 public void delete(String userid){
24
25 }
26
27
28
29 public void update(String username,String password){
30
31 }
32}
33 5.最后client端
package com.zyl.spring.client;
import com.zyl.spring.manager.UserManager;
public class Client {
/** *//**
* @param args
*/
public static void main(String[] args) {
UserManager.getInstace().save("haha", "1/Files/redcoatjk/S_1_NotSpring.zip");
}
}
这个写起来很麻烦啊.
运行client端的方法.
UserManager是单例,他的构造方法会在工厂中create一个userdao的实例(代码中创建的是mysql " return new UserDao4Mysql(); " )
然后调用mysql实例的save方法.打印出 here is mysql