中山市企业网站建设个体工商户能做网站吗
web/
2025/9/28 9:03:00/
文章来源:
中山市企业网站建设,个体工商户能做网站吗,做网站公司无锡,中国500强最新排名一、题目#xff1a;
在 Spring 项目中#xff0c;通过 main 方法获取到 Controller 类#xff0c;调用 Controller 里面通过注入的方式调用Service 类#xff0c;Service 再通过注入的方式获取到 Repository 类#xff0c;Repository 类里面有一个方法构建⼀个 User 对象…一、题目
在 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、具体实现
1User类
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 \ };}
}
2UserRepository类
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;}
}
3UserService类
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();}
}4UserController类
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());}
}
6运行结果 3、分析
1为什么main方法不能通过注入的方式获得UserController?
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/83242.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!