一、題目:
在 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());}
}