什么是Spring ?
Spring是以IOC(Inverse Of Control 控制反转) 和AOP(Aspect Oriented Programming 面向切面编程)为内核的轻量级、分层、松耦合的开源框架,提供了企业级编程复杂性的一站式解决方案, 是整合第三方开源技术的容器。
在idea中配置spring
1.首先在idea中新建一个maven项目
2.在pom.xml中配置spring依赖jar和junit依赖(junit用来测试)
<dependencies>
<!--spring依赖jar-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.19</version>
</dependency>
<!--junit包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
Spring的使用:
编写实体类User
在resources目录下创建spring配置文件 application.xml文件配置对象
导入以下数据:
<?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就是Java对象,控制权交给spring来管理 -->
<bean id="user" class="com.springconfigtest.entity.User">
</bean>
</beans>
编写测试类UserTest
获取对象的三种方式
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
//第一种强制类型转换
User user1 = (User) context.getBean("user");
System.out.println(user1);
//第二种通过反射获取
User user2 = context.getBean("user", User.class);
System.out.println(user2);
//第三种通过类型获取 可以省略id 当配置文件中同类型ean有多个这时候不能用类型获取,因此根
据情况选择合适的获取方式
User user3 = context.getBean(User.class);
System.out.println(user3);
注意:!!!在读取配置文件时,配置文件中所有bean都会被初始化!
User实体类添加无参构造方法(spring默认无参构造创建)
实体类的无参构造中输出无参构造执行了
通过测试类测试是否调用无参:
结果证明调用了默认调用了无参构造
User实体类添加有参构造方法(三种)
1.通过构造方法的名称初始化
2.通过构造方法的索引初始化
3.通过构造方法参数类型进行初始化
-
8种注入方式:
-
实体类 (要有get和set方法)
8种注入方式:
<bean id="date" class="java.util.Date"/>
<bean id="user2" class="com.hqyj.lls.entity.User">
<!--set注入-->
<!--1.常量注入-->
<property name="id" value="10"/>
<property name="name" value="wangmazi"/>
<property name="password" value="1234"/>
<!--2.对象注入-->
<property name="date" ref="date"/>
<!--3.null注入-->
<property name="isWife"><null/></property>
<!--4.数组注入-->
<property name="books">
<array>
<value>《《三国演义》》</value>
<value>《《红楼梦》》</value>
<value>《《哆啦A梦》》</value>
</array>
</property>
<!--5.list注入-->
<property name="hobby">
<list>
<value>篮球</value>
<value>唱跳</value>
<value>rap</value>
</list>
</property>
<!--6.set注入-->
<property name="sets">
<set>
<value>1</value>
<value>2</value>
<value>3</value>
</set>
</property>
<!--* 7.map注入-->
<property name="maps">
<map>
<entry key="c" value="3"/>
<entry key="a" value="4"/>
<entry key="o" value="5"/>
</map>
</property>
<!--*8. properties注入-->
<property name="properties">
<props>
<prop key="userDao">userDaoImpl</prop>
<prop key="userService">userServiceImpl</prop>
</props>
</property>
</bean>