找回密码
 立即注册
首页 业界区 业界 1、spring_helloworld

1、spring_helloworld

钤凑讪 2025-6-5 20:00:13
01、spring IOC基本使用
(1)使用maven的方式来构建项目
定义项目的groupId、artifactId
(2)添加对应的pom依赖

4.0.0
  1. <groupId>com.mashibing</groupId>
  2. springHelloword23</artifactId>
  3. <version>1.0-SNAPSHOT</version>
  4. <properties>
  5.     <maven.compiler.source>11</maven.compiler.source>
  6.     <maven.compiler.target>11</maven.compiler.target>
  7. </properties>
  8. <dependencies>
  9.     <dependency>
  10.         <groupId>org.springframework</groupId>
  11.         spring-context</artifactId>
  12.         <version>5.3.9</version>
  13.     </dependency>
  14. </dependencies>
复制代码
(3)编写配置1、实体类创建
Person.java
package com.mashibing.bean;
public class Person {
private Long id;
private String name;
private Integer age;
private String gender;
  1. public Person() {
  2. }
  3. public Person(Long id, String name, Integer age, String gender) {
  4.     this.id = id;
  5.     this.name = name;
  6.     this.age = age;
  7.     this.gender = gender;
  8. }
  9. @Override
  10. public String toString() {
  11.     return "Person{" +
  12.             "id=" + id +
  13.             ", name='" + name + '\'' +
  14.             ", age=" + age +
  15.             ", gender='" + gender + '\'' +
  16.             '}';
  17. }
  18. public Long getId() {
  19.     return id;
  20. }
  21. public void setId(Long id) {
  22.     this.id = id;
  23. }
  24. public String getName() {
  25.     return name;
  26. }
  27. public void setName(String name) {
  28.     this.name = name;
  29. }
  30. public Integer getAge() {
  31.     return age;
  32. }
  33. public void setAge(Integer age) {
  34.     this.age = age;
  35. }
  36. public String getGender() {
  37.     return gender;
  38. }
  39. public void setGender(String gender) {
  40.     this.gender = gender;
  41. }
复制代码
}
2、spring.xml配置
  1. [/code] [code]    <property name="id" value="3625221991********"></property>
  2.     <property name="name" value="单强"></property>
  3.     <property name="age" value="32"></property>
  4.     <property name="gender" value="男"></property>
  5. </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='男'}

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册