一、题目:
在 Spring 项目中,通过 main 方法获取到 Controller 类,调用 Controller 里面通过注入的方式调用Service 类,Service 再通过注入的方式获取到 Repository 类,Repository 类里面有一个方法构建⼀个 User 对象,返回给 main 方法。Repository 无需连接数据库,使用伪代码即可。
二、实现:
1、前置工作
(1)创建一个Maven项目
(2)添加Spring框架到pom.xml
(3)在resources下新建spring-config.xml,配置Spring
(3)创建好所需要的类
2、具体实现
(1)User类
package com.java.Ethan.Model;import org.springframework.stereotype.Component;public class User {private int id;private String name;public void setId(int id) {this.id = id;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +'}';}
}
(2)UserRepository类
package com.java.Ethan.Repository;import com.java.Ethan.Model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;@Repository
public class UserRepository {public User getUser() {User user = new User();user.setId(1);user.setName("张三");return user;}
}
(3)UserService类
package com.java.Ethan.Service;import com.java.Ethan.Model.User;
import com.java.Ethan.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class UserService {@Autowiredprivate UserRepository userRepository;public User getUser() {return userRepository.getUser();}
}
(4)UserController类
package com.java.Ethan.Controller;import com.java.Ethan.Model.User;
import com.java.Ethan.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;@Controller
public class UserController {@Autowiredprivate UserService userService;public User getUser() {return userService.getUser();}
}
(5)启动类
import com.java.Ethan.Controller.UserController;
import com.java.Ethan.Model.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class App {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");UserController userController = context.getBean("userController", UserController.class);System.out.println(userController.getUser().toString());}
}