依赖注入6(配置文件实现三层(自动注入))

本文介绍了一个基于Spring框架的简单示例,演示了如何通过配置文件实现接口和服务层之间的依赖注入。具体包括DAO接口及其实现类、Service接口及其实现类,并展示了如何在Spring配置文件中使用自动装配来绑定这些组件。

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

1.dao

package com.dao;

public interface UserDao {

 public void print();
}

 

2.daoImpl


 

package com.dao;

public class UserDaoImpl implements UserDao{

 @Override
 public void print() {
  System.out.println("userdaoImpl被调用");
 }
}

3.service

 

package com.service;

public interface UserService {

 public void print();
}

4.serviceImpl

package com.service;

import com.dao.UserDao;

public class UserServiceImpl implements UserService{

 private UserDao userdao1;

 public void setUserdao(UserDao userdao) {
  this.userdao1 = userdao;
 }
 @Override
 public void print() {
  userdao1.print();
 }
}

 

5.配置文件

<?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-4.3.xsd">
  
  <!-- <bean id="userdao" class="com.dao.UserDaoImpl"/>
  <bean id="userservice" class="com.service.UserServiceImpl">
   <property name="userdao" ref="userdao"></property>
  </bean> -->
  
  <!-- 当时通过名字使用自动装配时 userservice会自动找set函数名字一样的bean,而与属性名无关
   当定义在最上方的beans里面时,即装配所有的bean
  -->
  <bean id="userdao" class="com.dao.UserDaoImpl"/>
  <bean id="userservice" class="com.service.UserServiceImpl" autowire="byName"></bean>
</beans>

6.测试类

package com.Test;

import javax.faces.application.Application;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.service.UserService;
import com.service.UserServiceImpl;

public class test {

 public static void main(String [] arges) {
  
  ApplicationContext context=new ClassPathXmlApplicationContext("config.xml");
  UserService userService=(UserServiceImpl) context.getBean("userservice");
  userService.print();
 }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值