入门案例
创建项目
file -> 创建模块
![4f849e01764fc8ddf801c4aa8b6751a2.png](https://img-blog.csdnimg.cn/img_convert/4f849e01764fc8ddf801c4aa8b6751a2.png)
导入 Maven 依赖 和spring 核心配置文件
spring依赖的jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
核心文件
<?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> 标签交给底层new对象
<bean id="定义对象名字" class="被创建对象的全限定名">
</beans>
创建类, 创建测试类
public class Student {
private String name;
private Integer age;
}
简单的一个学生类,加2个属性 构建setter方法 重写toString方法
测试类
public class Test1 {
@Test//单元测试
public void test1(){
//获取核心文件
String config="applicationContext.xml";
//获取容器,传入核心文件,返回一个容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
//调用容器获取对象
Student model = (Student) ac.getBean("myStudent");
System.out.println("model="+ model);
}
}
在核心配置文件中 写set注入
<bean id="myStubent" class="com.tedu.ba01.Stubent">
<property name="age" value="20"/>
<property name="name" value="李四"/>
<!--property set属性注入 name属性对应pojo封装中的属性 value是赋予的值 一个property标签只能给一个属性赋值,
并且name 需要对应pojo中的set方法,如果找不到就会抛出异常 不管是构造方法 还是普通方法-->
</bean>
在set方法中如果没有this传值 属性的赋值也会失败
如果传的对象是复杂类型
<就是自己常见的对象的赋值> ref 的值等于 bean 中的id
<property name="school" ref="School"/>
然后这个对象也需要在 核心文件中 创建出来
<bean id="School" class="com.tedu.ba01.School">
<property name="name" value="深圳大学"/>
<property name="addr" value="保安"/>
构造方法注入
<bean id="myStubent" class="com.tedu.ba02.Stubent">
<constructor-arg name="name" value="sad"/>
<constructor-arg name="age" value="15"/>
<constructor-arg name="school" ref="School"/>
<!--构造方法的注入用的标签是 constructor-arg 内容一样-->
</bean>
<bean id="School" class="com.tedu.ba01.School">
<property name="name" value="深圳大学"/>
<property name="addr" value="保安"/>
</bean>
注解代替xml 完成di
步骤
- 在maven项目中注入 spring-context jar包依赖 ,他会把其他的jar一起带进来 而使用注解
需要有 spring_aop jar 包依赖
- 在类中加入注解
//等同与xml文件只中 的bean 标签 只有一个属性 value,可以不用写 在类上面 这里("myStudent")不写 ,默认名称为类名首字母小写
* 和@Component 功能一致的还有3个
* @Repository(用于持久层) 实现dao类 访问数据库
* @Service(用于业务层) 实现业务类 实现业务,可以有事务的功能
* @Controller (控制器) 实现控制器类 接受用户的请求 显示请求的处理结果
* 实现的语法和@Component 并由可以实现自己独有的功能
- 在配置文件中加入一个组件扫描器的标签,说明注解在你项目中的位置
<!--声明组件扫描器
base-package :指定注解在你的项目中的包名
base-package工作方式:spring会去扫描遍历 其指定包和子包中的所有类,找到注解,
按照类中的注解,实现功能
-->
<context:component-scan base-package="com.tedu.ba01"/>
<!--指定多个包的方式
1.创建多个扫描器
2.在 <context:component-scan base-package="com.tedu.ba01; com.tedu.ba02"/> 使用; 或 , 当分隔符
3.使用父包形式<context:component-scan base-package="com.tedu/> 但是最好不要太顶级的父包
,底层会扫描所有的子包,导致效率低下
-->