Spring初步配置1

    xiaoxiao2022-07-02  112

    1.需要导入的jar包

    spring依赖的包: 1. spring核心包: spring-core.jar spring-beans.jar spring-expression.jar spring-context.jar 2. 日志包: commons-logging.jar

    2.创建一个User类, 提供属性, 无参构造器, getter和setter, toString...

    package com.fpy.pojo; public class User { private String name; private int age; private String sex; @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; } 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 getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public User() { } public User(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; } }

    3.写配置文件

    1. 格式: xml 2. 命名: 无要求, 通常命名为 applicationContext.xml 3. 位置: 无要求, 通常放在类路径 <?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.fpy.pojo.User"> </bean> <bean id="user2" class="com.fpy.pojo.User"> </bean> </beans>

    4.测试

    package com.fpy.test; import com.fpy.pojo.User; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { //获取容器 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml"); //从容器中获取对象 User user = context.getBean("user", User.class); System.out.println(user); // 获取容器中所有对象的name String[] names = context.getBeanDefinitionNames(); for (String a : names) { System.out.println(a); } } }

    5.输出结果

    最新回复(0)