美文网首页
Spring详解(一)快速入门

Spring详解(一)快速入门

作者: 秀逼 | 来源:发表于2017-11-08 23:03 被阅读0次

创建配置文件:applicationContext.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"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd">

        <bean id="user" class="com.iotek.first.User"></bean>

</beans>

创建User类:

package com.iotek.first;

public class User {
    private int id;
    private String name;
    
    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;
    }
    
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + "]";
    }

}

创建测试类

package com.iotek.first;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) applicationContext.getBean("user");
        System.out.println(user);
    }

}

需要注意的是:这里的applicationContext.xml需要放置在src目录下,否则会报classpath not found异常,因为classpath默认是在src目录下开始查找的。

相关文章

网友评论

      本文标题:Spring详解(一)快速入门

      本文链接:https://www.haomeiwen.com/subject/lausmxtx.html