Spring是2003年兴起的一款轻量级的,非侵入式的IOC与AOP的一站式java开发框架,是为了简化企业级开发而诞生的,Spring通过IOC的思想可以将对象的控制权交给框架,在需要使用的该对象的时候由框架进行创建并调用
Spring HelleWord 搭建
1.导入Spring的jar包
<!-- spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
2.编写一个实体类并且配置Spring的配置文件
public class Admin {
private Integer id;
private String account;
public Admin() {
System.out.println("admin无参的构造方法");
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
@Override
public String toString() {
return "Admin{" +
"id=" + id +
", account='" + account + '\'' +
'}';
}
}
Spring.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 id="user" class="com.ff.spring.bean.User"> </bean>
</beans>
3.编写测试代码
public void springTest(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//不知道对象的类型时直接传入对象名获取
//Object obj = context.getBean("admin");
//清楚对象的类型时传入对象的类型直接获取
Admin admin = context.getBean("admin",Admin.class);
System.out.println(admin);
}