简单来说就是当自己需要一个对象的时候不需要自己手动去new一个,而是由其他容器来帮你提供;Spring里面就是IOC容器。
例如:
在Spring里面经常需要在Service这个装配一个Dao,一般是使用@Autowired 等注解:
首先遍历指定的包名:
1、调用构造方法自动初始化
2、jdom2读取配置bean.xml,
3、通过读取配置的bean.xml反射实例化读取的配置文件中的类和service;
cmd
进入E 盘
E:
进入相关文件目录
cd /src/main/java/com/spring
tree /f
tree /f F:\...\src\main\java\com\spring
------------------------------------------com.spring 包下文件结构
│ beans.xml
│ ClassPathXmlApplicationContext.java
│ UserServiceTest.java
│
├─dao
│ │ UserDAO.java
│ │
│ └─impl
│ UserDAOImpl.java
│
├─model
│ User.java
│
├─service
│ UserService.java
│
└─spingmn
BeanFactory.java
/*-------------------------------------------------------------------------------------------------------------------*/
UserDAO.java
package com.spring.dao;
import com.spring.dao.impl.UserDAOImpl;
import com.yang.dao.UserDao;
/**
* Created by Neusoft on 2019/10/21.
*/
public interface UserDAO {
public UserDao save(Object o);
}
/*-------------------------------------------------------------------------------------------------------------------*/
//UserDAOImpl.java
package com.spring.dao.impl;
import com.spring.dao.UserDAO;
import com.yang.dao.UserDao;
/**
* Created by Neusoft on 2019/10/21.
*/
public class UserDAOImpl implements UserDAO {
@Override
public UserDao save(Object o) {
System.out.println("调用DAO层 Save...");
return null;
}
}
/*-------------------------------------------------------------------------------------------------------------------*/
//User.java
package com.spring.model;
/**
* Created by Neusoft on 2019/10/21.
*/
public class User {
private long id;
private String name;
private String PWD;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPWD() {
return PWD;
}
public void setPWD(String PWD) {
this.PWD = PWD;
}
}
/*-------------------------------------------------------------------------------------------------------------------*/
//UserService.java
package com.spring.service;
import com.spring.model.User;
import com.spring.dao.UserDAO;
/**
* Created by Neusoft on 2019/10/21.
*/
public class UserService {
private UserDAO userDAO;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public void add(User u){
this.userDAO.save(u);
}
}
/*-------------------------------------------------------------------------------------------------------------------*/
//BeanFactory.java 重点面向接口编程
package com.spring.spingmn;
/**
* Created by Neusoft on 2019/10/21.
*/
publ