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 主类的包名.类名。

相关推荐
考虑考虑3 小时前
JDK25模块导入声明
java·后端·java ee
_小马快跑_5 小时前
Java 的 8 大基本数据类型:为何是不可或缺的设计?
java
Re_zero7 小时前
线上日志被清空?这段仅10行的 IO 代码里竟然藏着3个毒瘤
java·后端
洋洋技术笔记7 小时前
Spring Boot条件注解详解
java·spring boot
程序员清风1 天前
程序员兼职必看:靠谱软件外包平台挑选指南与避坑清单!
java·后端·面试
皮皮林5511 天前
利用闲置 Mac 从零部署 OpenClaw 教程 !
java
NE_STOP1 天前
springMVC-HTTP消息转换器与文件上传、下载、异常处理
spring
华仔啊1 天前
挖到了 1 个 Java 小特性:var,用完就回不去了
java·后端
SimonKing1 天前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
日月云棠2 天前
各版本JDK对比:JDK 25 特性详解
java