开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第2天
开始你的第一个Spring程序
按照惯例,我们第一个程序要求在控制台打印出:“Hello 何小幸, Welcome to Spring!”,实现步骤如下
第一步
在IDEA中创建新的Maven项目,然后在pom.xml文件中加载需要使用到的Spring四个基础包(spring-core-5.2.8.RELEASE.jar、spring-beans-5.2.8.RELEASE.jar、spring-context-5.2.8.RELEASE.jar、spring-expression-5.2.8.RELEASE.jar)以及Spring的一个依赖包(commons-logging-1.2.jar)
第二步
创建名为HelloSpring的类,在HelloSpring类中定义userName属性和show()方法
public class HelloSpring {
private String Username;
public void setUsername(String username) {
Username = username;
}
public void show(){
System.out.println("Hello " + this.Username + "Welcome to Spring!");
}
}
第三步
在resource文件中新建applicationContext.xml文件作为HelloSpring类的配置文件,并在该配置文件中创建id为helloSpring的Bean(管理对象),注意里面class要写全类名
如果上方有警告提示Application context not configured for this file,则要记得配置上下文:
File->Project Structure->modules->点开中间一排的包名->Spring->右侧一排左上方的加号->勾选中我们创建的配置文件->apply->OK
<?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="HelloSpring">
<!--为userName属性赋值-->
<property name="username" value="何小幸"></property>
</bean>
</beans>
第四步
创建测试类TestHelloSpring,在main()方法中初始化Spring容器并加载applicationContext.xml配置文件,通过Spring容器获取HelloSpring类的helloSpring实例,调用HelloSpring类中的show()方法在控制台输出信息。
public class TestHelloSpring {
public static void main(String[] args) {
//初始化spring容器,加载applicationContext.xml配置
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//通过容器获取配置中helloSpring的实例
HelloSpring helloSpring = (HelloSpring) applicationContext.getBean("helloSpring");
helloSpring.show();
}
}
如果这一步骤中ApplicationContext爆红表示类缺失,可能是因为maven源为国外,加载速度慢导致的,可在pom.xml中添加配置,使用阿里云类库
<repositories>
<repository>
<id>aliyunmaven</id>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
</repository>
</repositories>
配置好后,右键pom文件->maven->Reload project进行重新加载,若仍然报错,重启idea
最后,我们运行测试类,得到输出
在本案例中,我们就可以体会到,创建对象的过程由spring容器代我们实现,我们需要的只是去spring的配置文件中配置好相应的类,实现了解耦合的目的