今天主要学习用spring的四个基本包写一个helloword
首先新建一个java project 取名 spring-1并导入四个spring基本包
spring-core.jar,spring-beans,spring-context,spring-expression
在src目录下创建包com.ssm并新建类HelloSpring类具体代码如下
package com.ssm;
public class HelloSpring {
private int id;
private String userName;
private String password;
public HelloSpring() {
}
public HelloSpring(int id,String userName,String password) {
this.id = id;
this.userName = userName;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String userName) {
this.userName = userName;
}
public void show() {
System.out.println(id + ":欢迎您来学习spring框架");
System.out.println(id+userName+password);
}
}
接下来是配置文件在src目录下创建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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloSpring" class="com.ssm.HelloSpring">
<!-- collaborators and configuration for this bean go here -->
<!-- <property name="username" value="张三"></property>-->
<constructor-arg name="id" value="2019"></constructor-arg>
<constructor-arg name="userName" value="我想有個"></constructor-arg>
<constructor-arg name="password" value="女朋友"></constructor-arg>
</bean>
</beans>
最后是测试文件TestHelloSpring了
package com.ssm;
import org.springframework.context.ApplicationContext;
public class TestHelloSpring {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloSpring helloSpring = (HelloSpring)ctx.getBean("helloSpring");
helloSpring.show();
}
}
运行结果大致就是最后这样
最后spring框架的核心机制就是IoC(控制反转)容器,也可以称作依赖注入(DI)