spring的IOC

提供UserService的接口和实现类

获得UserService实现类的实例

public interface UserService {
	
	public void addUser();

}

public class UserServiceImpl implements UserService {

	@Override
	public void addUser() {
		System.out.println("a_ico add user");
	}

}


若不用spring 直接new一个对象即可

用spring 则将由Spring创建对象实例--> IoC 控制反转(Inverse of  Control)

之后需要实例对象时,从spring工厂(容器)中获得,需要将实现类的全限定名称配置到xml文件中 或者 @Autowired注解


配置文件

 位置:任意,开发中一般在classpath下(src)

 名称:任意,开发中常用applicationContext.xml

 内容:添加schema约束

<?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">
	<!-- 配置service 
		<bean> 配置需要创建的对象
			id :用于之后从spring容器获得实例时使用的
			class :需要创建实例的全限定类名
	-->
	<bean id="userService" class="com.lp.a_ioc.UserServiceImpl"></bean>
</beans>



@Test
	public void demo02(){
		//从spring容器获得
		//1 获得容器
		String xmlPath = "com/lp/a_ioc/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		//2获得内容 --不需要自己new,都是从spring容器获得
		UserService userService = (UserService) applicationContext.getBean("userService");
		userService.addUser();
		
	}


基于注解

@Autowired
private UserService userService;

public void test(){
        userService.addUser();
}



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值