spring的第一个核心功能 ioc
ioc :控制反转,把对象的创建,赋值,管理工作都交给代码之外的容器实现。
使用 ioc : 目的就是减少对代码的改动, 也能实现不同的功能。 实现解耦合。
第一个Spring程序
创建Spring需要的依赖
<!-- 加入Spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.8</version>
</dependency>
创建一个User类
public class User {
//生成set方法
public void setName(String name) {
this.name = name;
}
public void setPswd(String pswd) {
this.pswd = pswd;
}
//重写toString
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", pswd='" + pswd + '\'' +
'}';
}
//用户名
private String name;
//用户密码
private String pswd;
}
创建spring需要使用的配置文件
<?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 id="User" class="com.blb.jx.test.day01.User">
//赋值
<property name="name" value="张三"/>
<property name="pswd" value="123"/>
</bean>
</beans>
创建一个测试类
public class UserTest {
//测试类的注解
@Test
public void test01(){
//创建Spring容器的对象
//"app.xml" 指定Spring配置文件的名称
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("app.xml");
User user = (User) applicationContext.getBean("User");
//打印输出
System.out.println(user);
}
}
输出结果s
User{name='张三', pswd='123'}
使用注解方式
@Component("User")
public class User {
public void setName(String name) {
this.name = name;
}
public void setPswd(String pswd) {
this.pswd = pswd;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", pswd='" + pswd + '\'' +
'}';
}
@Value("王五")
private String name;
@Value("123456")
private String pswd;
}
创建扫描器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--创建扫描器-->
<context:component-scan base-package="com.blb.jx.test.day07"/>
</beans>
创建测试类
public class UserText {
@Test
public void test(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("day07/app07.xml");
User user = (User) applicationContext.getBean("User");
System.out.println(user);
}
}
最终结果
User{name='王五', pswd='123456'}