Spring创建的步骤

1.导入相关架包

 2.创建dao包,在dao包中创建一个接口,再创建一个操作类实现接口并重写接口中的方法    创建接口可以提升代码的扩展性

//创建接口
public interface UsersDao {
    public void findById();
}

//创建一个类实现接口,重写接口中的方法
public class UsersDaoImp implements UsersDao{
    public void findById(){
        System.out.println("=======findById==========");
    }
}

3.创建一个service包,在service包中创建一个接口,再创建一个操作类实现接口并重写接口中的方法     创建接口可以提升代码的扩展性

//创建接口
public interface UsersService {    
    public void serviceFindById();
}

//创建接口实现类,重写接口中的方法
public class UsersServiceImp implements UsersService{
    private UsersDao usersDao;

    public UsersDao getUsersDao() {
        return usersDao;
    }

    public void setUsersDao(UsersDao usersDao) {
        this.usersDao = usersDao;
    }
    public void serviceFindById() {
        usersDao.findById();
    }
}

4.创建一个controller包,在该包创建类写入如下代码:

public class UsersController {
    private UsersService usersService;

    public UsersService getUsersService() {
        return usersService;
    }

    public void setUsersService(UsersService usersService) {
        this.usersService = usersService;
    }
    public void find() {
        usersService.serviceFindById();
    }
}

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.xsd">

    <bean id="usersController" class="com.zhiyou100.mcl.controller.UsersController">
        <property name="usersService" ref="usersServiceImp"></property>
    </bean>
    <bean id="usersServiceImp" class="com.zhiyou100.mcl.service.UsersServiceImp">
        <property name="usersDao" ref="usersDaoImp"></property>
        
    </bean>
    <bean id="usersDaoImp" class="com.zhiyou100.mcl.dao.UsersDaoImp"></bean>
</beans>

6.测试

public class Test {
    public static void main(String[] args) {
        ApplicationContext app=new ClassPathXmlApplicationContext("app.xml");
        UsersController uc = (UsersController) app.getBean("usersController");
        uc.find();
    }
}
原文地址:https://www.cnblogs.com/mcl2238973568/p/11478200.html