首页 > 其他分享 >Spring框架的构建

Spring框架的构建

时间:2024-10-27 12:48:22浏览次数:1  
标签:框架 Spring helloSpring HelloSpring hello bean 构建 public

Spring技术

1.Spring的设计理念是基于bean的编程
2.Spring的两大核心技术
控制翻转(ioc)/依赖注入(di)
面向切面编程(Aop)

控制翻转/依赖注入

1.业务逻辑层与数据层高度耦合
例如:
2.创建对象的控制权转移给工厂
将依赖的对象注入到需要的类中去,是“控制翻转”设计思想的具体实现
例如:

总结

传统方式调用组件类

public class TestHello {
    public static void main(String[] args) {
        // 实例化对象
        HelloSpring helloSpring = new HelloSpring();
        helloSpring.setHello("Hello World!");
        // 执行print()方法
        helloSpring.print();
    }
}
将 HelloSpring helloSpring = new HelloSpring();
与 helloSpring.setHello("Hello World!");交给bean组件实现

3.如何实现控制翻转

3.1依赖包
3.2编写bean组件类如:

bean组件类:HelloSpring
public class HelloSpring {
	// 定义hello属性,该属性的值将通过Spring框架进行设置
	private String hello = null;

	/**
	 * 打印方法,从Spring配置文件中获取属性并输出。
	 */
	public void print() {
		System.out.println("Spring say:" + this.getHello() + "!");
}

	public String getHello() {
		return hello;
	}

	public void setHello(String hello) {
		this.hello = hello;
	}
}

3.3编写Spring配置文件

Spring配置文件:applicationContext.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"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xmlns:p="http://www.springframework.org/schema/p"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd">

	<bean id="helloSpring" class="com.szit.lab3.springdemo.HelloSpring">
		<!-- property元素用来为实例的属性赋值,此处实际是调用setWho()方法实现赋值操作 -->
		<property name="hello">
			<!-- 此处将字符串"Spring"赋值给who属性 -->
            <!-- 亦或者用p标签 -->  
			<value>反转的人生,如此惊艳</value>
		</property>
	</bean>
</beans>

3.4编写测试类文件

编写测试类文件: TestSpringHello
public class TestSpringHello {
    public static void main(String[] args) {
        // 通过ClassPathXmlApplicationContext实例化Spring的上下文
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        // 通过ApplicationContext的getBean()方法,根据id来获取bean的实例
        HelloSpring helloSpring = (HelloSpring) context.getBean("helloSpring");
        // 执行print()方法
        helloSpring.print();
    }
}

标签:框架,Spring,helloSpring,HelloSpring,hello,bean,构建,public
From: https://www.cnblogs.com/wsjBK/p/18508155

相关文章