一、准备工作
1、环境
- 开发工具:idea社区版
- Java版本:jdk8
- maven:3.5.2
- spring版本:5.1.4.RELEASE
- 基础包名:xyz.dava.study
2、基础maven配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>xyz.dava.study</groupId>
<artifactId>study-spring</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.version>5.1.4.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--fastjson 不是必须,仅是为了方便打印对象-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>RELEASE</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
- 后面的内容都会在此pom配置的基础上进行添加修改
3、Let's go
为了方便打印对象,我们先建一个xyz.dava.study.beans.BaseBean
的父类,实现如下:
package xyz.dava.study.beans;
import com.alibaba.fastjson.JSON;
public abstract class BaseBean {
@Override
public String toString() {
return JSON.toJSONString(this);
}
}
正式开始啦
现在有这么一个类xyz.dava.study.beans.impl.Bean1
,实现如下:
package xyz.dava.study.beans.impl;
import xyz.dava.study.beans.BaseBean;
public class Bean1 extends BaseBean {
}
此处为了演示,里面并没有任何字段方法
我们要获取这个类的示例该怎么办呢?
- 不使用spring:
package xyz.dava.study;
import xyz.dava.study.beans.impl.Bean1;
public class Main {
public static void main(String[] args) {
Bean1 bean1 = new Bean1();
System.out.println(bean1);
}
}
打印结果{}
注意
由于篇幅所限,下文中的java代码包定义和导包部分代码都会省略
- 使用spring
spring需要一个配置文件才会,把你要托管的类告诉spring,这里直接给出
<?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="beans1" class="xyz.dava.study.beans.impl.Bean1"/>
</beans>
java代码如下:
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Bean1 beans1 = context.getBean("beans1", Bean1.class);
System.out.println(beans1);
}
}
运行结果仍然是{}
至此,spring的helloworld到此结束
ps:好像没看到helloworld
网友评论