01、spring IOC基本使用
(1)使用maven的方式来构建项目
定义项目的groupId、artifactId
(2)添加对应的pom依赖
4.0.0- <groupId>com.mashibing</groupId>
- springHelloword23</artifactId>
- <version>1.0-SNAPSHOT</version>
- <properties>
- <maven.compiler.source>11</maven.compiler.source>
- <maven.compiler.target>11</maven.compiler.target>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework</groupId>
- spring-context</artifactId>
- <version>5.3.9</version>
- </dependency>
- </dependencies>
复制代码 (3)编写配置1、实体类创建
Person.java
package com.mashibing.bean;
public class Person {
private Long id;
private String name;
private Integer age;
private String gender;- public Person() {
- }
- public Person(Long id, String name, Integer age, String gender) {
- this.id = id;
- this.name = name;
- this.age = age;
- this.gender = gender;
- }
- @Override
- public String toString() {
- return "Person{" +
- "id=" + id +
- ", name='" + name + '\'' +
- ", age=" + age +
- ", gender='" + gender + '\'' +
- '}';
- }
- public Long getId() {
- return id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- 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;
- }
- public String getGender() {
- return gender;
- }
- public void setGender(String gender) {
- this.gender = gender;
- }
复制代码 }
2、spring.xml配置
- [/code] [code] <property name="id" value="3625221991********"></property>
- <property name="name" value="单强"></property>
- <property name="age" value="32"></property>
- <property name="gender" value="男"></property>
- </bean>
复制代码 3、编写测试类测试类SpringDemoTest.javapublic class SpringDemoTest {
public static void main(String[] args) {
//ApplicationContext:表示ioc容器
//ClassPathXmlApplicationContext:表示从当前classpath路径中获取xml文件的配置
//根据spring的配置文件来获取ioc容器对象
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Person person = context.getBean("person", Person.class);
System.out.println(person);
}
}
4,测试结果
Person{id=3625221991********, name='单强', age=32, gender='男'}
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |