Spring---HelloWorld
此处不使用Maven搭建
下载Jar包 Apache Commons Logging API
下载所需Spring框架库
解压
Eclipse创建普通Java项目
效果
添加必需的库
最后,确定应用即可
效果
代码
package org.yun.domain;
import java.util.Date;
public class User {
private String name;
private Integer age;
private String message;
private Date date;
public void say() {
System.out.println("我是"+ this.name + ",今年" + this.age + ",于此时---->" + this.date +this.message );
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", message=" + message + ", date=" + date + "]";
}
}
<?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-3.0.xsd">
<!--
Spring将所有的Java对象都看成了bean,通过spring容器进行管理
bean元素用来声明spring的一个对象(bean)
id属性可理解为引用变量,必须唯一
class为 类的全限名(包名+类名)
property元素表示属性,name表示属性名(此处是set方法)
User user = new User();
-->
<bean id="user" class="org.yun.domain.User">
<property name="name" value="青龙"></property>
<property name="age" value="999"></property>
<property name="message" value=",用Spring说了第一个HelloWorld."></property>
<property name="date" ref="d"></property>
</bean>
<!-- Date d = new Date() -->
<bean id="d" class="java.util.Date"/>
</beans>
package org.yun.controller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.yun.domain.User;
public class HelloworldController {
/**
* 通过spring容器获取bean
* */
public static void main(String[] args) {
// 解析/applicationContext.xml文件,创建spring容器,将文件中的bean初始化并放入容器
ApplicationContext context = new ClassPathXmlApplicationContext("/applicationContext.xml");
// <bean id="user" 根据id获取对应的bean
User user = (User)context.getBean("user");
System.out.println(user);
user.say();
}
}
结果:
User [name=青龙, age=999, message=,用Spring说了第一个HelloWorld., date=Thu Jul 11 19:26:26 CST 2019]
我是青龙,今年999,于此时---->Thu Jul 11 19:26:26 CST 2019,用Spring说了第一个HelloWorld.
附带参考
链接:https://pan.baidu.com/s/1FlQ1CSq6Y9285VGh-f7ZYg
提取码:62ic