初识Spring(一)

mac2025-11-16  4

初识Spring

对于初次接触spring的人来说,首先要了解Spring框架的优点: (1)非入侵式设计 可以使应用程序代码对框架的依赖最小化 (2)方便解耦,简化开发 降低组件之间的耦合性是非常有用的。 耦合是指两个或两个以上的体系或两种运动形式间通过相互作用而彼此影响以至联合起来的现象,解耦就是解除耦合关系,简而言之就是就是一个功能的代码不要写在另一个的功能代码中,如果两者之间需要交互,可以通过接口,通过消息,甚至可以引入框架,但总之就是不要直接交叉写。 (3)支持AOP 允许将一些通用任务,如安全、事务、日志等进行集中式处理,从而提高程序的复用性。 (4)支持声明式事务处理、方便程序测试、方便集成各种优秀框架等

第一次实例操作

此处笔者使用IDEA进行spring的入门程序展示

首先创建spring的配置文件(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"> <!-- 将指定类配置给spring,让spring创建其实例对象 --> <bean id="service" class="com.tf.spring.service.Service"/> </beans>

创建接口:

package com.tf.spring.service.impl; public interface ServiceImpl { void sayHello(); }

其次创建接口的实现类:

package com.tf.spring.service; import com.tf.spring.service.impl.ServiceImpl; public class Service implements ServiceImpl { @Override public void sayHello() { System.out.println("Service Say Hello"); } }

最后创建测试类:

package com.tf.spring; import com.tf.spring.service.impl.ServiceImpl; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { public static void main(String[] args) { //初始化spring容器,加载配置文件 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //调用容器获取service实例 ServiceImpl service = (ServiceImpl)context.getBean("service"); //实现实例的方法 service.sayHello(); } }

结果如下: 创建途中会遇到各种问题,待后续补充…

我不是鸽,我是累了,咕.jpg

最新回复(0)