Spring的核心基础:感受一下对象工厂

"欢迎来到Spring!"的小项目

(1)写一个HelloSpring的类,采用setter方法注入userName,写一个简单的show方法。

java 复制代码
package com.itzhoutao;
public class  HelloSpring{
	private String userName;

	public void setUserName(String userName)
	{
		this.userName = userName;
	}

	public void show(){
		System.out.println(userName + ":欢迎来到Spring!");
	}

}

(2)利用Spring容器,如ApplicationContext,初始化容器,加载xml配置,获取(getBean)实例。写了一个TestHelloSpring类。

java 复制代码
package com.itzhoutao;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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();//调用方法
    }

}

3.applicatiomContext.xml的信息:

java 复制代码
<?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">
    <!-- 将指定类配置给Spring,让Spring创建HelloSpring对象的实例 -->
    <bean id="helloSpring" class="com.itzhoutao.HelloSpring">
        <!--为userName属性赋值-->
        <property name="userName" value="土豆哥哥"></property>
    </bean>
</beans>

手动管理j的ar包和这个项目的基本结构:

jar包在springlibs目录下,相关程序代码写在了work目录下。

手动编译运行Spring项目的方法:

  1. 将Spring所需的所有jar包(含commons-logging的jar包)文件放到C:\Program Files\Java\jre1.8.0_181\lib\ext的目录下,并另外存放一份放到源码所在位置的springlibs目录下。

  2. 将所有的.java源码文件放到某个工作文件夹比如work中(注意只要.java的文件,不要包名对应的文件夹),将所需的xml配置文件也拷贝到本文件夹中。

  3. 进入work工作文件夹,然后在命令行下运行编译命令:javac -d . *.java -encoding utf8 -classpath ..\springlibs\* 即可成功编译。

  4. 运行:在work工作文件夹中,运行命令:java 主类的包名.类名。

相关推荐
80530单词突击赢8 分钟前
C++关联容器深度解析:set/map全攻略
java·数据结构·算法
兩尛15 分钟前
c++知识点1
java·开发语言·c++
舟舟亢亢17 分钟前
JVM复习笔记——下
java·jvm·笔记
rainbow688919 分钟前
Python学生管理系统:JSON持久化实战
java·前端·python
有味道的男人32 分钟前
1688获得商品类目调取商品榜单
java·前端·spring
独自破碎E36 分钟前
【中心扩展法】LCR_020_回文子串
java·开发语言
不光头强37 分钟前
spring boot项目欢迎页设置方式
java·spring boot·后端
4311媒体网1 小时前
自动收藏功能的实现方法
java·开发语言
Yana.nice1 小时前
证书格式的适用场景与核心对比
java·linux