Spring的HelloWorld
Posted dingcx2013
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring的HelloWorld相关的知识,希望对你有一定的参考价值。
①创建Java工程
②添加Spring包到CLASSPATH中,主要的jar包包括
commons-logging-1.1.3.jar (Spring的jar依赖该包)
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
③创建bean类Book(eclipse中ctrl+o查看类的成员)
package com.dcx.spring.bean; public class Book { private Integer id; private String name; private String author; private double price; public Book() { super(); } public Book(Integer id, String name, String author, double price) { super(); this.id = id; this.name = name; this.author = author; this.price = price; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Book [id=" + id + ", name=" + name + ", author=" + author + ", price=" + price + "]"; } }
④为Book创建Spring的bean配置文件,该文件放置在项目的src文件夹下,项目结构如下
beans.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="book" class="com.dcx.spring.bean.Book"> <property name="id" value="1" /> <property name="name" value="活着" /> <property name="author" value="余华" /> <property name="price" value="15.8" /> </bean> </beans>
⑤建立测试类
package junit.test; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.dcx.spring.bean.Book; public class TestIOC { private ApplicationContext ioc; @Before public void setUp(){ //通过加载XML文件来创建ioc容器 ioc = new ClassPathXmlApplicationContext("beans.xml"); } @After public void tearDown(){
//关闭ioc AbstractApplicationContext acc = (AbstractApplicationContext)ioc; acc.close(); } @Test public void test01() { //获取bean对象 Book book = (Book)ioc.getBean("book"); System.out.println(book); } }
⑥查看测试结果,成功获取bean对象
以上是关于Spring的HelloWorld的主要内容,如果未能解决你的问题,请参考以下文章
Spring boot:thymeleaf 没有正确渲染片段
初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段
初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段
spring源码阅读笔记之HelloWorld和spring第一步ClassPathXMLApplicationContext
spring练习,在Eclipse搭建的Spring开发环境中,使用set注入方式,实现对象的依赖关系,通过ClassPathXmlApplicationContext实体类获取Bean对象(代码片段