练习
在 Spring 项⽬中,通过 main ⽅法获取到 Controller 类,调⽤ Controller ⾥⾯通过注⼊的⽅式调⽤ Service 类,Service 再通过注⼊的⽅式获取到 Repository 类,Repository 类⾥⾯有⼀个⽅法构建⼀个 User 对象,返回给 main ⽅法。Repository ⽆需连接数据库,使⽤伪代码即可。
User类
package com.java.demo.model;
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
UserController类
package com.java.demo.controller;
import com.java.demo.model.User;
import com.java.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
@Autowired
private UserService userService;
public User getUser() {
return userService.getUser();
}
}
UserRepository类
package com.java.demo.repository;
import com.java.demo.model.User;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository {
public User getUser() {
// 伪代码
User user = new User();
user.setId(1);
user.setName("张三");
return user;
}
}
UserService类
package com.java.demo.service;
import com.java.demo.model.User;
import com.java.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUser() {
return userRepository.getUser();
}
}
App类文章来源:https://www.toymoban.com/news/detail-612858.html
package com.java.demo;
import com.java.demo.controller.UserController;
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());
}
}
文章来源地址https://www.toymoban.com/news/detail-612858.html
到了这里,关于【Spring框架】Spring读取与存储综合练习的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!