spring IOC基本使用
1、Spring_helloworld
使用maven的方式来构建项目
-
创建maven项目
定义项目的groupId、artifactId
-
添加对应的pom依赖
pom.xml
<dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.3.RELEASE</version> </dependency> </dependencies>
-
编写代码
Person.java
package com.mashibing.bean; public class Person { private int id; private String name; private int age; private String gender; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", gender='" + gender + '\'' + '}'; } }
-
测试
MyTest.java
import com.mashibing.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
Person person = (Person) context.getBean("person");
System.out.println(person);
}
}
总结:
搭建spring项目需要注意的点:
1、一定要将配置文件添加到类路径中,使用idea创建项目的时候要放在resource目录下.
细节点:
1、ApplicationContext就是IOC容器的接口,可以通过此对象获取容器中创建的对象
2、对象在Spring容器创建完成的时候就已经创建完成,不是需要用的时候才创建
3、对象在IOC容器中存储的时候都是单例的,如果需要多例需要修改属性
4、创建对象给属性赋值的时候是通过setter方法实现的
5、对象的属性是由setter/getter方法决定的,而不是定义的成员属性