当前位置: 首页 > 知识库问答 >
问题:

如何在带有注释配置的spring mvc中使用spring数据

郗缪文
2023-03-14

我在我的项目中使用spring data jpa和spring mvc。然而,我总是得到错误。
如果我注释jpaconfig.java,我的应用程序运行良好。
我不知道为什么?请你帮帮我:

我的代码:

package com.example.system.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class ConfigInitializer implements WebApplicationInitializer {

    private static final String DISPATCHER_SERVLET_NAME = "dispatcher";

    public void onStartup(ServletContext servletContext)
            throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebAppConfig.class);
        servletContext.addListener(new ContextLoaderListener(ctx));

        ctx.setServletContext(servletContext);

        ServletRegistration.Dynamic servlet = servletContext.addServlet(DISPATCHER_SERVLET_NAME,
                new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }
}

WebAppConfig.java

package com.example.system.config;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan("com.example")
public class WebAppConfig extends WebMvcConfigurerAdapter {

    /**
     * Configure ViewResolvers to deliver preferred views.
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        registry.viewResolver(viewResolver);
    }
    /**
     * Configure MessageSource to lookup any validation/error message in internationalized property files
     */
    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    }
}

jpaconfig.java

package com.example.system.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@PropertySource("classpath:db/application.properties")
@EnableTransactionManagement
@EnableJpaRepositories("com.example.repository")
public class JpaConfig {
    private static final String PROPERTY_NAME_DATABASE_DRIVER = "jdbc.driverClassName";
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "jdbc.password";
    private static final String PROPERTY_NAME_DATABASE_URL = "jdbc.url";
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "jdbc.username";

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
    @Resource
    private Environment env;

    @Bean(destroyMethod = "close")
    public DataSource dataSource() {
        HikariConfig dataSource = new HikariConfig();
        dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setJdbcUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
        dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
        dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
        return new HikariDataSource(dataSource);
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
        entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter());
        entityManagerFactoryBean.setJpaProperties(hibProperties());

        return entityManagerFactoryBean;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        return new HibernateJpaVendorAdapter();
    }

    private Properties hibProperties() {
        Properties properties = new Properties();
        properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
        return properties;
    }

    @Bean
    @Autowired
    public JpaTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

}

应用程序.属性

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:db11g
jdbc.username=username
jdbc.password=password

hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-update
hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
hibernate.format_sql=true
entitymanager.packages.to.scan=com.example.entity
package com.example.entity;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Date;

@Entity
@Table(name = "USER")    
public class User {
    @Id
    @Column(name = "id")
    @SequenceGenerator(name = "seq", sequenceName = "user_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
    @Getter @Setter
    private long id;

    @Column(name = "userCode", nullable = false, length = 20)
    @Getter @Setter
    private String userCode;

    @Column(name = "name", nullable = false, length = 20)
    @Getter @Setter
    private String name;
}
package com.example.repository;

import com.example.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByEmail(String email);

    List<User> findByEmailAndPassword(String email, String password);
}
...
    @Service("userService")
    public class UserServiceImpl implements UserService {
        @Autowired
        private UserRepository userRepository;
    @Transactional(readOnly = true)
        @Override
        public User findUserByEmail(String email) throws ServiceException {
            List<User> users = userRepository.findByEmail(email);
            if (users.size() == 1) {
                return users.get(0);
            } else if(!users.isEmpty()) {
                Log.SERVICE_LOG.info("Duplicated email found!!! Email: " + email);
            }
            throw new ResourceNotFoundException("Cannot find any user with email: " + email);
        }
    }
...

共有1个答案

江烨伟
2023-03-14

您可以尝试将@repository添加到userrepository接口吗?

 类似资料:
  • 问题内容: 不合理,无法通过注释而不是纯XML Bean来配置Spring Bean,现在我正面临后果。 我使用以下方式配置REST通道 现在,我只需要简单地将设置为仅将此具有非null值的字段输出到JSON。我尝试了以下方法: Bean被创建,但是转换器的另一个实例已创建并在通道中使用。所以我已经尝试过这种方法并在Stackoverflow问题中进行了描述,但是json序列化仍然使用其自己的配置

  • 最后,我尝试通过 但我以结束。所以现在我别无选择,所以我在这里征求任何想法。如何控制和配置框架使用的映射器?

  • 我是Spring调度器的新手。我读了很多关于@ScheduledExecutorService和TimerTask的文章。 因此,据我所知,@ScheduledExecutorService和ScheduledExecutorService的功能大部分是相同的,但如果您的代码是在spring中,那么最好在代码中使用@ScheduledExecutorService。 所以我的问题是,假设我想在15

  • 问题内容: 我很好奇弹簧注入如何处理带有注释的调用方法。如果我在方法上添加注释并返回实例,则我理解这告诉spring通过调用方法并获取返回的实例来创建bean。但是,有时必须使用该bean来连接其他bean或设置其他代码。完成此操作的通常方法是调用带注释的方法以获取实例。我的问题是,为什么这不会导致有多个bean实例漂浮? 例如,请参见下面的代码(取自另一个问题)。该方法带有注释,因此我可以想象s

  • 我正在尝试使用Enunciate为我的REST API生成静态文档,该API是使用Spring MVC 3.2用Java编写的。Enuncite网站声称,它通过使用以下特定插件来支持Spring: http://enunciate.codehaus.org/module_spring_app.html 在查看配置选项时,看起来我应该导入一个spring applicationContext.xml

  • 我是一个新的Spring,并在某些方面被卡住了,如下所述- 我有一个类color,它有两个不同的实现名,分别是Red和Blue,我想使用将这两个实现名都注入color列表中。 但将异常获取为 自动连线依赖项的注入失败;嵌套异常为org.springframework.beans.factory.beanCreationException:无法自动连接字段:private java.util.lis