1.创建Spring项目
总共分为三步:
1.创建⼀个普通 Maven 项⽬。
2.添加 Spring 框架⽀持(spring-context、spring-beans)
3.添加启动类
1.1创建一个Maven项目
1.2添加Spring框架支持
在项目的pom.xml中添加以下依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
1.3添加启动类
在创建好的项目的Java文件下创建一个启动类,包含main方法即可
public class App {
public static void main(String[] args) {
}
}
2.存储Bean对象
2.1创建Bean
public class User {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public void sayHI(){
System.out.println("hi");
}
}
2.2将Bean注射到容器
创建一个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">
</beans>
将User对象注册到Spring中:
id是唯一的
<bean id="user" class="com.bite.User"></bean>
3.获取并使用User对象
3.1创建Spring上下文
使用ApplicationContext
ApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
使用BeanFactory
BeanFactory factory=new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
ApplicationContext和BeanFactory的区别:
共同点:都是获得Spring bean
不同点:
1.ApplicationContext是BeanFactory的子类
子类有的功能,父类都有。国际化、环境、资源文件管理……
2.性能
ApplicationContext提前把bean全部加载完,使用时直接取就可以了(空间换时间)
BeanFactory时懒加载方式,使用时才去创建。
3.2获取指定的Bean对象
Bean的id要一一对应
//Spring的运行环境
ApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
//1.通过getBean(String var1)获取对象
User user=(User) context.getBean("user");
user.sayHI();
<bean id="user" class="com.bite.User">
获取bean的其他方式:
//2.通过getBean(Class<T> var1)获取对象
User user2=context.getBean(User.class);
user2.sayHI();
优点:不需要进行类型转换
缺点:如果一个类有多个对象时,不能使用该方式
//3.通过getBean(String var1,Class<T> var2)来获取bean
User user3=context.getBean("user1", User.class);
user3.sayHI();
这几种方式获取的都是同一个对象
3.3总结
操作流程