【问题标题】:correct structure in MVC with spring带有弹簧的MVC中的正确结构
【发布时间】:2021-11-22 11:29:20
【问题描述】:

我对正确的 mvc 模式有点困惑。

这是我的配置文件:在这个类中,我有所有的 Bean。

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = " name.web.controller")
@PropertySource("classpath:NewLibrary.properties")
@EnableTransactionManagement

    @Bean
    public UserRepo getUserService() {
        return new UserImpl(getDataSource());
    }
    
    
    @Bean
    public BookRepo getBookService() {
        return new BookImpl(getDataSource());
    }

这是我的 UserRepo 接口和 UserService 接口。他们是一样的

public interface UserService {
public String getUser();
void add(UserModel u);
UserModel getById(int id);
UserModel getByName(String name);
UserModel getByCognome(String surname);
Optional<UserModel> findOne(int id);
public void insert(User u);
public String giveName();
List<UserModel>ByNome(String nome);
List<UserModel> ByPassAndUsername(String password, String username);

}

我的类实现了这个接口

@Repository
public class UserImpl extends AbstractDao<UserModel, Integer> implements UserRepo {
@PersistenceContext
private EntityManager em;
 @Autowired
public UserRepo userRepo;

private JdbcTemplate conn;
@Override
@Transactional
public void add(UserModel u) {
    em.persist(u);
}
public UserImpl(DataSource ds) {
    conn= new JdbcTemplate(ds);
}
@Override
public UserModel getById(int id) {
    return em.find(UserModel.class, id);
}
@Override
public UserModel getByName(String nome) {
    CriteriaBuilder queryBuilder= em.getCriteriaBuilder();
    CriteriaQuery<UserModel> query= 
queryBuilder.createQuery(UserModel.class);
    Root<UserModel> rec= query.from(UseriModel.class);
     
query.select(rec).where(queryBuilder.equal(rec.get("nome"), nome));
     
     UserModel ut=em.createQuery(query).getSingleResult();
     em.clear();
    
     return ut;
    
    //return em.find(UtentiModel.class, nome);
    
};

最后我得到了我的控制器 在我的控制器中,我 @Autowired UsersRepo/这是一个接口/。 而且我的代码有效,我可以做所有的 CRUD 操作。

但是,有人告诉我这不是正确的方法。我不能直接自动接线。 @Autowired 的 UserRepo,在 Controller 类中。 所以我在网上搜索信息,然后创建一个服务类。 它是这样创建的服务:具有与我在 UserRepo 接口中编写的相同方法的相同接口。在我创建了实现该接口的类之后,称为 UserServiceImpl。

在 userServiceImpl 中,我转到 @Autowire UserRepo 接口,然后在 Controller 中转到 @Autowire userService。

但现在我的代码不起作用,我在所有控件的所有页面中都得到 404 状态:`请求的资源 [/bookProject/] 不可用

描述源服务器没有找到目标资源的当前表示或不愿意透露存在的表示。`

我在控制台中没有错误,只有信息:

INFO: Command line argument: -Dfile.encoding=UTF-8
set 30, 2021 5:41:10 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The Apache Tomcat Native library which allows using OpenSSL was not found on the java.library.path: [/usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib]
set 30, 2021 5:41:10 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
set 30, 2021 5:41:10 PM org.apache.catalina.startup.Catalina load
INFO: Server initialization in [624] milliseconds
set 30, 2021 5:41:10 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
set 30, 2021 5:41:10 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.50]
set 30, 2021 5:41:12 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
set 30, 2021 5:41:12 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
set 30, 2021 5:41:12 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory [/home/viktoriya/Scrivania/apache-tomcat-9.0.50/webapps/ROOT]
 set 30, 2021 5:41:12 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory [/home/viktoriya/Scrivania/apache-tomcat-9.0.50/webapps/ROOT] has finished in [13] ms
set 30, 2021 5:41:12 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
set 30, 2021 5:41:12 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in [2050] milliseconds

所以我无法理解 Autowire 某些 bean 是否错误,或者我当前的模式是否错误,或者我是否需要更改配置类中的某些内容,或者我是否没有很好地应用服务类。因为在我的代码运行良好之前。

这是我的控制器: @控制器 公共类用户控制器 { @自动连线 私人用户服务我们; 列出用户; @GetMapping("/new") public ModelAndView new(模型模型) {

UserModel users= new UserModel();
model.addAttribute("utenteForm", user);
return new ModelAndView("client", "utenteForm", new 
UtentiModel());
}
@PostMapping("/add")
public ModelAndView sumbit(@ModelAttribute("utenteForm") UserModel users)
{ us.ad(users);

这是 UserServiceImpl:

@Service
public class UserServiceImpl implements UserService{
private final static Logger log= 
Logger.getLogger(UserServiceImpl.class.getName());
@Autowired
private UserRepo userRepo;
@PersistenceContext
private EntityManager em;
@Override
public void add(UserModel u) {
    userRepo.add(u);
}
@Override
public UserModel getByName(String name) {
    
    return userRepo.getByName(name);
}

【问题讨论】:

  • 首先验证是否存在映射到bookProject 端点的控制器方法。如果是这样,请编辑您的帖子以包含它。
  • 请发布您的服务接口及其实现,以及更新的控制器。
  • @SB 完成。与此同时,我也尝试更改代码并将新类的 Autowired 放在任何地方,但它不起作用
  • @TheHeadRush 我为这个问题添加了更多代码

标签: java spring spring-mvc model-view-controller javabeans


【解决方案1】:

我会说检查您根据控制器定义调用的路径。我认为如果您更新代码以查看控制器会有所帮助。

例子:

@RestController
@RequestMapping("/test")
public class TestRestController{

  @Autowired
  private TestService testService;
 .....
}

 @Service
public class TestServiceImpl implements TestService {

  @Autowired    
  private TestRepository testRepository;

}
@Repository
@Transactional
 public class TestRepositoryImpl implements TestRepository{
 
 }

【讨论】:

  • 如果我删除 UserService 和 UserServiceImpl 或者如果我不自动装配它们,我的代码就会开始工作,但在这种情况下它们没有被使用。如果我离开这 2 个类并将它们自动装配到 Controller 中,则没有任何效果。既不是调试模式。如果我在控制器中自动装配这个新类,我有 500 个状态,没有找到 bean。如果我不在控制器内部自动装配 UserRepo,那么一切正常。所以我认为这是bean的问题,但不知道问题到底出在哪里。更改新类的自动装配我的错误范围从 404 到 500。
  • 我可以在这里给你写一个小方法,你可以定义控制器、服务、存储库,然后你可以将它与你的代码进行比较。它还可以帮助您在调试时设置日志级别,可能会静默失败。
  • 请。我会检查我哪里出错了
  • 我添加到我的答案中,因为无法将它放在 cmets 中。我希望它有所帮助。否则我认为我需要查看更多代码。
  • 你能把@Autowired放在服务中的testRepository上吗?
猜你喜欢
  • 2018-07-27
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
  • 1970-01-01
  • 2015-06-26
  • 2011-05-03
相关资源
最近更新 更多