《Spring 系列》- 作用域

本文通过一个简单的示例展示了如何使用Spring框架进行依赖注入。示例中定义了一个UserService接口及其实现类UserServiceImpl,并通过applicationContext.xml配置文件来管理这些Bean的生命周期。此外,还演示了如何根据不同作用域获取Bean实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目结构

111433_DJPz_2330610.png

build.gradle

apply plugin:'java'

repositories{
	maven{
		url 'http://maven.aliyun.com/nexus/content/groups/public/'
	}
}

dependencies{
	compile group: 'org.springframework', name: 'spring-context', version: '3.2.3.RELEASE' 
}

UserService.java

public interface UserService {
	public void addUser();
}

UserServiceImpl.java

public class UserServiceImpl implements UserService {

	@Override
	public void addUser() {
		System.out.println("UserServiceImpl#addUser");
	}
}

applicationContext.xml

<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="userServiceId1" class="com.kimisme.UserServiceImpl"></bean>
	<bean id="userServiceId2" class="com.kimisme.UserServiceImpl" scope="prototype"></bean>
</beans> 

Program.java

public class Program {
	public static void main(String[] args) {
		String xmlPath="com/kimisme/applicationContext.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		
		UserService userService11 = applicationContext.getBean("userServiceId1",UserService.class);
		UserService userService12 = applicationContext.getBean("userServiceId1",UserService.class);
		System.out.println(userService11==userService12);
		
		UserService userService21 = applicationContext.getBean("userServiceId2",UserService.class);
		UserService userService22 = applicationContext.getBean("userServiceId2",UserService.class);
		System.out.println(userService21==userService22);
	}
}

输出

true
false

 

转载于:https://my.oschina.net/kimisme/blog/1612813

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值