我们理解了IOC的基本思想,我们现在来看下Spring的应用:
第一个Spring程序在普通三层架构的基础上,将程序修改为 Spring框架程序
public interface UserDao {
void getUser();
}
impl
public class UserDaoImpl implements UserDao {
@Override
public void getUser() {
System.out.println("你好");
}
}
service
interface
public interface UserService {
void getUser();
}
impl
public class UserServiceImpl implements UserService{
private UserDao userDao;
// 利用set实现
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void getUser() {
userDao.getUser();
}
}
test
public class Mytest {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
userService.setUserDao(new UserDaoImpl());
userService.getUser();
}
}
dao追加impl
public class UserDaoOneImpl implements UserDao{
@Override
public void getUser() {
System.out.println("你好One");
}
}
在父工程导入依赖
创建Spring配置文件org.springframework spring-webmvc 5.1.10.RELEASE
Spring配置文件的文件名可以随意,但Spring建议的名称为applicationContext.xml。这里我们命名为beans.xml并放在resource目录下
springtest
import com.huang.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class FirstTest {
public static void main(String[] args) {
//解析beans.xml文件 , 生成管理相应的Bean对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//getBean : 参数即为spring配置文件中bean的id .
Hello hello = (Hello) context.getBean("hello");
hello.show();
}
}
spring配置文件一览
Spring 配置文件支持两种格式,即 XML 文件格式和 Properties 文件格式。
- Properties 配置文件主要以 key-value 键值对的形式存在,只能赋值,不能进行其他操作,适用于简单的属性配置。
- XML 配置文件是树形结构,相对于 Properties 文件来说更加灵活。XML配置文件结构清晰,但是内容比较繁琐,适用于大型复杂的项目。
| 属性名称 | 描述 |
|---|---|
| id | 是一个 Bean 的唯一标识符,Spring 容器对 Bean 的配置和管理都通过该属性完成 |
| name | Spring 容器同样可以通过此属性对容器中的 Bean 进行配置和管理,name 属性中可以为 Bean 指定多个名称,每个名称之间用逗号或分号隔开 |
| class | 该属性指定了 Bean 的具体实现类,它必须是一个完整的类名,使用类的全限定名 |
| scope | 用于设定 Bean 实例的作用域,其属性值有 singleton(单例)、prototype(原型)、request、session 和 global Session。其默认值是 singleton |
| constructor-arg | |
| property | |
| ref | |
| value | |
| list | 用于封装 List 或数组类型的依赖注入 |
| set | 用于封装 Set 类型属性的依赖注入 |
| map | 用于封装 Map 类型属性的依赖注入 |
| entry |
id:该属性是 Bean 实例的唯一标识,程序通过 id 属性访问 Bean,Bean 与 Bean 间的依赖关系也是通过 id 属性关联的。
如果没有配置id,name就是默认标识符
如果配置id,又配置了name,那么name是别名
name可以设置多个别名,可以用逗号,分号,空格隔开
如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;
class:指定该 Bean 所属的类,注意这里只能是类,不能是接口。全限定名=包名+类名
其他配置(了解)alias 设置别名 , 为bean设置别名 , 可以设置多个别名
团队的合作通过import来实现 .



