Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如何启动3.2+;在javaconfig上正确休眠4_Spring_Hibernate_Spring Java Config - Fatal编程技术网

Spring 如何启动3.2+;在javaconfig上正确休眠4

Spring 如何启动3.2+;在javaconfig上正确休眠4,spring,hibernate,spring-java-config,Spring,Hibernate,Spring Java Config,我想在Spring3.2+Hibernate4+javaconfig中进行测试 build.gradle的内容是下一个: buildscript { repositories { mavenCentral() } dependencies { classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.9' } } apply plugin: 'eclipse' appl

我想在Spring3.2+Hibernate4+javaconfig中进行测试

build.gradle的内容是下一个:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.9'
    }
}

apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'war'
apply plugin: 'tomcat'

ext.springVersion =       '3.2.4.RELEASE'
ext.springMobileVersion = '1.1.0.RELEASE'
ext.thymeleafVersion =    '2.0.19'
ext.aspectJVersion =      '1.6.9'
ext.cglibVersion =        '2.2'
ext.slf4jVersion =        '1.6.1'
ext.servletJstlVersion =  '1.2'
ext.servletApiVersion =   '3.0.1'
ext.servletJspVersion =   '2.1'
ext.junitVersion =        '4.11'
ext.tomcatVersion =       '7.0.42'
ext.pgsqlVersion =        '9.1-901.jdbc4'
ext.mockiteoCoreVersion = '1.9.5'
ext.mailVersion         = '1.4.7'
ext.dataBindVersion     = '2.2.3'
ext.hbVersion           = '4.2.7.Final'
ext.guavaVersion        = '15.0'
ext.javassistVersion    = '3.18.0-GA'

war {
    webInf {
        include "src/main/webapp/resources/**"
    }
}

dependencies {
    compile("org.springframework:spring-context:$springVersion") {
        exclude module: 'commons-logging'
    }
    compile "org.springframework:spring-context-support:$springVersion"
    compile "org.springframework:spring-web:$springVersion"
    compile "org.springframework:spring-webmvc:$springVersion"
    compile "org.springframework.mobile:spring-mobile-device:$springMobileVersion"
    compile "org.springframework:spring-tx:$springVersion"
    compile "org.springframework:spring-orm:$springVersion"

    compile "com.fasterxml.jackson.core:jackson-databind:$dataBindVersion"
    compile "javax.mail:mail:$mailVersion"
    compile "org.thymeleaf:thymeleaf-spring3:$thymeleafVersion"
    compile "org.aspectj:aspectjrt:$aspectJVersion"
    compile "cglib:cglib-nodep:$cglibVersion"
    compile "javax.inject:javax.inject:1"
    compile "org.slf4j:slf4j-api:$slf4jVersion"
    compile "org.slf4j:jcl-over-slf4j:$slf4jVersion"
    compile "org.slf4j:slf4j-log4j12:$slf4jVersion"
    compile "javax.servlet:jstl:$servletJstlVersion"
    providedCompile("javax.servlet:javax.servlet-api:$servletApiVersion")
    providedCompile("javax.servlet.jsp:jsp-api:$servletJspVersion")

    // Persistence
    compile "postgresql:postgresql:$pgsqlVersion"
    compile "org.hibernate:hibernate-core:$hbVersion"
    compile "org.hibernate:hibernate-entitymanager:$hbVersion"
    compile "org.apache.tomcat:tomcat-dbcp:$tomcatVersion"
    compile "org.javassist:javassist:$javassistVersion"

    // Tools
    compile "com.google.guava:guava:$guavaVersion"

    // TEST
    testCompile "junit:junit:$junitVersion"
    testCompile "org.mockito:mockito-core:$mockiteoCoreVersion"
    testCompile "org.springframework:spring-test:$springVersion"
    testCompile "org.hamcrest:hamcrest-core:1.3"
    testCompile "org.hamcrest:hamcrest-library:1.3"
    testCompile "org.apache.commons:commons-lang3:3.1"

    // TOMCAT
    tomcat("org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion",
            "org.apache.tomcat.embed:tomcat-embed-logging-juli:$tomcatVersion")
    tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:$tomcatVersion") {
        exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj'
    }
}

repositories {
    mavenCentral()
    maven { url 'http://repo.spring.io/libs-release' }
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.8'
}
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:pgsql.properties" })
@ComponentScan(basePackages = {"com.example.persistence"})
public class PersistenceConfig
{
    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource()
    {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory()
    {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.example.persistence.domain" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public HibernateTransactionManager transactionManager()
    {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory().getObject());
        return txManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation()
    {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties hibernateProperties() {
        return new Properties() {
            {
                setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
                setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
                setProperty("hibernate.globally_quoted_identifiers", "true");
            }
        };
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceConfig.class})
public class ProductServiceTest
{
    private static final Logger LOG = LoggerFactory.getLogger(ProductServiceTest.class);

    @Autowired
    private ProductService productService;

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public final void listApplicationBeans() throws Exception
    {
        List<String> beans = Arrays.asList(applicationContext.getBeanDefinitionNames());
        for (String bean: beans)
        {
            LOG.info(String.format("--> App Beans [%s]", bean));
        }
    }
}
# jdbc
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://some_address:5432/some_database
jdbc.user=someuser
jdbc.pass=somepassword

# hibernate
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
@Entity
public class Product implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String name;

    public long getId()
    {
        return id;
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Product(String name)
    {
        setName(name);
    }

    @Override
    public String toString()
    {
        StringBuilder builder = new StringBuilder();

        builder.append(Product.class.getSimpleName()).append(" [\n");
        builder.append("id = ").append(id).append("\n");
        builder.append("name = ").append(name).append("\n");
        builder.append("]");

        return builder.toString();
    }

}
import org.springframework.stereotype.Repository;
import com.example.persistence.dao.common.AbstractDao;
import com.example.persistence.domain.Product;
@Repository
public class ProductDao extends AbstractDao<Product>
{
    public ProductDao()
    {
        super();
        setClazz(Product.class);
    }
}
@Service
public class ProductService extends AbstractService<Product>
{
    @Autowired
    private ProductDao dao;

    public ProductService()
    {
        super();
    }

    @Override
    protected IOperation<Product> getDao()
    {
        return dao;
    }
}
PersistenceConfig内容是下一个:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.9'
    }
}

apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'war'
apply plugin: 'tomcat'

ext.springVersion =       '3.2.4.RELEASE'
ext.springMobileVersion = '1.1.0.RELEASE'
ext.thymeleafVersion =    '2.0.19'
ext.aspectJVersion =      '1.6.9'
ext.cglibVersion =        '2.2'
ext.slf4jVersion =        '1.6.1'
ext.servletJstlVersion =  '1.2'
ext.servletApiVersion =   '3.0.1'
ext.servletJspVersion =   '2.1'
ext.junitVersion =        '4.11'
ext.tomcatVersion =       '7.0.42'
ext.pgsqlVersion =        '9.1-901.jdbc4'
ext.mockiteoCoreVersion = '1.9.5'
ext.mailVersion         = '1.4.7'
ext.dataBindVersion     = '2.2.3'
ext.hbVersion           = '4.2.7.Final'
ext.guavaVersion        = '15.0'
ext.javassistVersion    = '3.18.0-GA'

war {
    webInf {
        include "src/main/webapp/resources/**"
    }
}

dependencies {
    compile("org.springframework:spring-context:$springVersion") {
        exclude module: 'commons-logging'
    }
    compile "org.springframework:spring-context-support:$springVersion"
    compile "org.springframework:spring-web:$springVersion"
    compile "org.springframework:spring-webmvc:$springVersion"
    compile "org.springframework.mobile:spring-mobile-device:$springMobileVersion"
    compile "org.springframework:spring-tx:$springVersion"
    compile "org.springframework:spring-orm:$springVersion"

    compile "com.fasterxml.jackson.core:jackson-databind:$dataBindVersion"
    compile "javax.mail:mail:$mailVersion"
    compile "org.thymeleaf:thymeleaf-spring3:$thymeleafVersion"
    compile "org.aspectj:aspectjrt:$aspectJVersion"
    compile "cglib:cglib-nodep:$cglibVersion"
    compile "javax.inject:javax.inject:1"
    compile "org.slf4j:slf4j-api:$slf4jVersion"
    compile "org.slf4j:jcl-over-slf4j:$slf4jVersion"
    compile "org.slf4j:slf4j-log4j12:$slf4jVersion"
    compile "javax.servlet:jstl:$servletJstlVersion"
    providedCompile("javax.servlet:javax.servlet-api:$servletApiVersion")
    providedCompile("javax.servlet.jsp:jsp-api:$servletJspVersion")

    // Persistence
    compile "postgresql:postgresql:$pgsqlVersion"
    compile "org.hibernate:hibernate-core:$hbVersion"
    compile "org.hibernate:hibernate-entitymanager:$hbVersion"
    compile "org.apache.tomcat:tomcat-dbcp:$tomcatVersion"
    compile "org.javassist:javassist:$javassistVersion"

    // Tools
    compile "com.google.guava:guava:$guavaVersion"

    // TEST
    testCompile "junit:junit:$junitVersion"
    testCompile "org.mockito:mockito-core:$mockiteoCoreVersion"
    testCompile "org.springframework:spring-test:$springVersion"
    testCompile "org.hamcrest:hamcrest-core:1.3"
    testCompile "org.hamcrest:hamcrest-library:1.3"
    testCompile "org.apache.commons:commons-lang3:3.1"

    // TOMCAT
    tomcat("org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion",
            "org.apache.tomcat.embed:tomcat-embed-logging-juli:$tomcatVersion")
    tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:$tomcatVersion") {
        exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj'
    }
}

repositories {
    mavenCentral()
    maven { url 'http://repo.spring.io/libs-release' }
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.8'
}
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:pgsql.properties" })
@ComponentScan(basePackages = {"com.example.persistence"})
public class PersistenceConfig
{
    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource()
    {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory()
    {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.example.persistence.domain" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public HibernateTransactionManager transactionManager()
    {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory().getObject());
        return txManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation()
    {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties hibernateProperties() {
        return new Properties() {
            {
                setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
                setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
                setProperty("hibernate.globally_quoted_identifiers", "true");
            }
        };
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceConfig.class})
public class ProductServiceTest
{
    private static final Logger LOG = LoggerFactory.getLogger(ProductServiceTest.class);

    @Autowired
    private ProductService productService;

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public final void listApplicationBeans() throws Exception
    {
        List<String> beans = Arrays.asList(applicationContext.getBeanDefinitionNames());
        for (String bean: beans)
        {
            LOG.info(String.format("--> App Beans [%s]", bean));
        }
    }
}
# jdbc
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://some_address:5432/some_database
jdbc.user=someuser
jdbc.pass=somepassword

# hibernate
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
@Entity
public class Product implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String name;

    public long getId()
    {
        return id;
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Product(String name)
    {
        setName(name);
    }

    @Override
    public String toString()
    {
        StringBuilder builder = new StringBuilder();

        builder.append(Product.class.getSimpleName()).append(" [\n");
        builder.append("id = ").append(id).append("\n");
        builder.append("name = ").append(name).append("\n");
        builder.append("]");

        return builder.toString();
    }

}
import org.springframework.stereotype.Repository;
import com.example.persistence.dao.common.AbstractDao;
import com.example.persistence.domain.Product;
@Repository
public class ProductDao extends AbstractDao<Product>
{
    public ProductDao()
    {
        super();
        setClazz(Product.class);
    }
}
@Service
public class ProductService extends AbstractService<Product>
{
    @Autowired
    private ProductDao dao;

    public ProductService()
    {
        super();
    }

    @Override
    protected IOperation<Product> getDao()
    {
        return dao;
    }
}
ProductServiceTest内容是下一个:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.9'
    }
}

apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'war'
apply plugin: 'tomcat'

ext.springVersion =       '3.2.4.RELEASE'
ext.springMobileVersion = '1.1.0.RELEASE'
ext.thymeleafVersion =    '2.0.19'
ext.aspectJVersion =      '1.6.9'
ext.cglibVersion =        '2.2'
ext.slf4jVersion =        '1.6.1'
ext.servletJstlVersion =  '1.2'
ext.servletApiVersion =   '3.0.1'
ext.servletJspVersion =   '2.1'
ext.junitVersion =        '4.11'
ext.tomcatVersion =       '7.0.42'
ext.pgsqlVersion =        '9.1-901.jdbc4'
ext.mockiteoCoreVersion = '1.9.5'
ext.mailVersion         = '1.4.7'
ext.dataBindVersion     = '2.2.3'
ext.hbVersion           = '4.2.7.Final'
ext.guavaVersion        = '15.0'
ext.javassistVersion    = '3.18.0-GA'

war {
    webInf {
        include "src/main/webapp/resources/**"
    }
}

dependencies {
    compile("org.springframework:spring-context:$springVersion") {
        exclude module: 'commons-logging'
    }
    compile "org.springframework:spring-context-support:$springVersion"
    compile "org.springframework:spring-web:$springVersion"
    compile "org.springframework:spring-webmvc:$springVersion"
    compile "org.springframework.mobile:spring-mobile-device:$springMobileVersion"
    compile "org.springframework:spring-tx:$springVersion"
    compile "org.springframework:spring-orm:$springVersion"

    compile "com.fasterxml.jackson.core:jackson-databind:$dataBindVersion"
    compile "javax.mail:mail:$mailVersion"
    compile "org.thymeleaf:thymeleaf-spring3:$thymeleafVersion"
    compile "org.aspectj:aspectjrt:$aspectJVersion"
    compile "cglib:cglib-nodep:$cglibVersion"
    compile "javax.inject:javax.inject:1"
    compile "org.slf4j:slf4j-api:$slf4jVersion"
    compile "org.slf4j:jcl-over-slf4j:$slf4jVersion"
    compile "org.slf4j:slf4j-log4j12:$slf4jVersion"
    compile "javax.servlet:jstl:$servletJstlVersion"
    providedCompile("javax.servlet:javax.servlet-api:$servletApiVersion")
    providedCompile("javax.servlet.jsp:jsp-api:$servletJspVersion")

    // Persistence
    compile "postgresql:postgresql:$pgsqlVersion"
    compile "org.hibernate:hibernate-core:$hbVersion"
    compile "org.hibernate:hibernate-entitymanager:$hbVersion"
    compile "org.apache.tomcat:tomcat-dbcp:$tomcatVersion"
    compile "org.javassist:javassist:$javassistVersion"

    // Tools
    compile "com.google.guava:guava:$guavaVersion"

    // TEST
    testCompile "junit:junit:$junitVersion"
    testCompile "org.mockito:mockito-core:$mockiteoCoreVersion"
    testCompile "org.springframework:spring-test:$springVersion"
    testCompile "org.hamcrest:hamcrest-core:1.3"
    testCompile "org.hamcrest:hamcrest-library:1.3"
    testCompile "org.apache.commons:commons-lang3:3.1"

    // TOMCAT
    tomcat("org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion",
            "org.apache.tomcat.embed:tomcat-embed-logging-juli:$tomcatVersion")
    tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:$tomcatVersion") {
        exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj'
    }
}

repositories {
    mavenCentral()
    maven { url 'http://repo.spring.io/libs-release' }
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.8'
}
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:pgsql.properties" })
@ComponentScan(basePackages = {"com.example.persistence"})
public class PersistenceConfig
{
    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource()
    {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory()
    {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.example.persistence.domain" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public HibernateTransactionManager transactionManager()
    {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory().getObject());
        return txManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation()
    {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties hibernateProperties() {
        return new Properties() {
            {
                setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
                setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
                setProperty("hibernate.globally_quoted_identifiers", "true");
            }
        };
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceConfig.class})
public class ProductServiceTest
{
    private static final Logger LOG = LoggerFactory.getLogger(ProductServiceTest.class);

    @Autowired
    private ProductService productService;

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public final void listApplicationBeans() throws Exception
    {
        List<String> beans = Arrays.asList(applicationContext.getBeanDefinitionNames());
        for (String bean: beans)
        {
            LOG.info(String.format("--> App Beans [%s]", bean));
        }
    }
}
# jdbc
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://some_address:5432/some_database
jdbc.user=someuser
jdbc.pass=somepassword

# hibernate
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
@Entity
public class Product implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String name;

    public long getId()
    {
        return id;
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Product(String name)
    {
        setName(name);
    }

    @Override
    public String toString()
    {
        StringBuilder builder = new StringBuilder();

        builder.append(Product.class.getSimpleName()).append(" [\n");
        builder.append("id = ").append(id).append("\n");
        builder.append("name = ").append(name).append("\n");
        builder.append("]");

        return builder.toString();
    }

}
import org.springframework.stereotype.Repository;
import com.example.persistence.dao.common.AbstractDao;
import com.example.persistence.domain.Product;
@Repository
public class ProductDao extends AbstractDao<Product>
{
    public ProductDao()
    {
        super();
        setClazz(Product.class);
    }
}
@Service
public class ProductService extends AbstractService<Product>
{
    @Autowired
    private ProductDao dao;

    public ProductService()
    {
        super();
    }

    @Override
    protected IOperation<Product> getDao()
    {
        return dao;
    }
}
产品内容是下一个:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.9'
    }
}

apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'war'
apply plugin: 'tomcat'

ext.springVersion =       '3.2.4.RELEASE'
ext.springMobileVersion = '1.1.0.RELEASE'
ext.thymeleafVersion =    '2.0.19'
ext.aspectJVersion =      '1.6.9'
ext.cglibVersion =        '2.2'
ext.slf4jVersion =        '1.6.1'
ext.servletJstlVersion =  '1.2'
ext.servletApiVersion =   '3.0.1'
ext.servletJspVersion =   '2.1'
ext.junitVersion =        '4.11'
ext.tomcatVersion =       '7.0.42'
ext.pgsqlVersion =        '9.1-901.jdbc4'
ext.mockiteoCoreVersion = '1.9.5'
ext.mailVersion         = '1.4.7'
ext.dataBindVersion     = '2.2.3'
ext.hbVersion           = '4.2.7.Final'
ext.guavaVersion        = '15.0'
ext.javassistVersion    = '3.18.0-GA'

war {
    webInf {
        include "src/main/webapp/resources/**"
    }
}

dependencies {
    compile("org.springframework:spring-context:$springVersion") {
        exclude module: 'commons-logging'
    }
    compile "org.springframework:spring-context-support:$springVersion"
    compile "org.springframework:spring-web:$springVersion"
    compile "org.springframework:spring-webmvc:$springVersion"
    compile "org.springframework.mobile:spring-mobile-device:$springMobileVersion"
    compile "org.springframework:spring-tx:$springVersion"
    compile "org.springframework:spring-orm:$springVersion"

    compile "com.fasterxml.jackson.core:jackson-databind:$dataBindVersion"
    compile "javax.mail:mail:$mailVersion"
    compile "org.thymeleaf:thymeleaf-spring3:$thymeleafVersion"
    compile "org.aspectj:aspectjrt:$aspectJVersion"
    compile "cglib:cglib-nodep:$cglibVersion"
    compile "javax.inject:javax.inject:1"
    compile "org.slf4j:slf4j-api:$slf4jVersion"
    compile "org.slf4j:jcl-over-slf4j:$slf4jVersion"
    compile "org.slf4j:slf4j-log4j12:$slf4jVersion"
    compile "javax.servlet:jstl:$servletJstlVersion"
    providedCompile("javax.servlet:javax.servlet-api:$servletApiVersion")
    providedCompile("javax.servlet.jsp:jsp-api:$servletJspVersion")

    // Persistence
    compile "postgresql:postgresql:$pgsqlVersion"
    compile "org.hibernate:hibernate-core:$hbVersion"
    compile "org.hibernate:hibernate-entitymanager:$hbVersion"
    compile "org.apache.tomcat:tomcat-dbcp:$tomcatVersion"
    compile "org.javassist:javassist:$javassistVersion"

    // Tools
    compile "com.google.guava:guava:$guavaVersion"

    // TEST
    testCompile "junit:junit:$junitVersion"
    testCompile "org.mockito:mockito-core:$mockiteoCoreVersion"
    testCompile "org.springframework:spring-test:$springVersion"
    testCompile "org.hamcrest:hamcrest-core:1.3"
    testCompile "org.hamcrest:hamcrest-library:1.3"
    testCompile "org.apache.commons:commons-lang3:3.1"

    // TOMCAT
    tomcat("org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion",
            "org.apache.tomcat.embed:tomcat-embed-logging-juli:$tomcatVersion")
    tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:$tomcatVersion") {
        exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj'
    }
}

repositories {
    mavenCentral()
    maven { url 'http://repo.spring.io/libs-release' }
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.8'
}
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:pgsql.properties" })
@ComponentScan(basePackages = {"com.example.persistence"})
public class PersistenceConfig
{
    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource()
    {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory()
    {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.example.persistence.domain" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public HibernateTransactionManager transactionManager()
    {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory().getObject());
        return txManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation()
    {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties hibernateProperties() {
        return new Properties() {
            {
                setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
                setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
                setProperty("hibernate.globally_quoted_identifiers", "true");
            }
        };
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceConfig.class})
public class ProductServiceTest
{
    private static final Logger LOG = LoggerFactory.getLogger(ProductServiceTest.class);

    @Autowired
    private ProductService productService;

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public final void listApplicationBeans() throws Exception
    {
        List<String> beans = Arrays.asList(applicationContext.getBeanDefinitionNames());
        for (String bean: beans)
        {
            LOG.info(String.format("--> App Beans [%s]", bean));
        }
    }
}
# jdbc
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://some_address:5432/some_database
jdbc.user=someuser
jdbc.pass=somepassword

# hibernate
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
@Entity
public class Product implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String name;

    public long getId()
    {
        return id;
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Product(String name)
    {
        setName(name);
    }

    @Override
    public String toString()
    {
        StringBuilder builder = new StringBuilder();

        builder.append(Product.class.getSimpleName()).append(" [\n");
        builder.append("id = ").append(id).append("\n");
        builder.append("name = ").append(name).append("\n");
        builder.append("]");

        return builder.toString();
    }

}
import org.springframework.stereotype.Repository;
import com.example.persistence.dao.common.AbstractDao;
import com.example.persistence.domain.Product;
@Repository
public class ProductDao extends AbstractDao<Product>
{
    public ProductDao()
    {
        super();
        setClazz(Product.class);
    }
}
@Service
public class ProductService extends AbstractService<Product>
{
    @Autowired
    private ProductDao dao;

    public ProductService()
    {
        super();
    }

    @Override
    protected IOperation<Product> getDao()
    {
        return dao;
    }
}
ProductDao内容是下一个:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.9'
    }
}

apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'war'
apply plugin: 'tomcat'

ext.springVersion =       '3.2.4.RELEASE'
ext.springMobileVersion = '1.1.0.RELEASE'
ext.thymeleafVersion =    '2.0.19'
ext.aspectJVersion =      '1.6.9'
ext.cglibVersion =        '2.2'
ext.slf4jVersion =        '1.6.1'
ext.servletJstlVersion =  '1.2'
ext.servletApiVersion =   '3.0.1'
ext.servletJspVersion =   '2.1'
ext.junitVersion =        '4.11'
ext.tomcatVersion =       '7.0.42'
ext.pgsqlVersion =        '9.1-901.jdbc4'
ext.mockiteoCoreVersion = '1.9.5'
ext.mailVersion         = '1.4.7'
ext.dataBindVersion     = '2.2.3'
ext.hbVersion           = '4.2.7.Final'
ext.guavaVersion        = '15.0'
ext.javassistVersion    = '3.18.0-GA'

war {
    webInf {
        include "src/main/webapp/resources/**"
    }
}

dependencies {
    compile("org.springframework:spring-context:$springVersion") {
        exclude module: 'commons-logging'
    }
    compile "org.springframework:spring-context-support:$springVersion"
    compile "org.springframework:spring-web:$springVersion"
    compile "org.springframework:spring-webmvc:$springVersion"
    compile "org.springframework.mobile:spring-mobile-device:$springMobileVersion"
    compile "org.springframework:spring-tx:$springVersion"
    compile "org.springframework:spring-orm:$springVersion"

    compile "com.fasterxml.jackson.core:jackson-databind:$dataBindVersion"
    compile "javax.mail:mail:$mailVersion"
    compile "org.thymeleaf:thymeleaf-spring3:$thymeleafVersion"
    compile "org.aspectj:aspectjrt:$aspectJVersion"
    compile "cglib:cglib-nodep:$cglibVersion"
    compile "javax.inject:javax.inject:1"
    compile "org.slf4j:slf4j-api:$slf4jVersion"
    compile "org.slf4j:jcl-over-slf4j:$slf4jVersion"
    compile "org.slf4j:slf4j-log4j12:$slf4jVersion"
    compile "javax.servlet:jstl:$servletJstlVersion"
    providedCompile("javax.servlet:javax.servlet-api:$servletApiVersion")
    providedCompile("javax.servlet.jsp:jsp-api:$servletJspVersion")

    // Persistence
    compile "postgresql:postgresql:$pgsqlVersion"
    compile "org.hibernate:hibernate-core:$hbVersion"
    compile "org.hibernate:hibernate-entitymanager:$hbVersion"
    compile "org.apache.tomcat:tomcat-dbcp:$tomcatVersion"
    compile "org.javassist:javassist:$javassistVersion"

    // Tools
    compile "com.google.guava:guava:$guavaVersion"

    // TEST
    testCompile "junit:junit:$junitVersion"
    testCompile "org.mockito:mockito-core:$mockiteoCoreVersion"
    testCompile "org.springframework:spring-test:$springVersion"
    testCompile "org.hamcrest:hamcrest-core:1.3"
    testCompile "org.hamcrest:hamcrest-library:1.3"
    testCompile "org.apache.commons:commons-lang3:3.1"

    // TOMCAT
    tomcat("org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion",
            "org.apache.tomcat.embed:tomcat-embed-logging-juli:$tomcatVersion")
    tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:$tomcatVersion") {
        exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj'
    }
}

repositories {
    mavenCentral()
    maven { url 'http://repo.spring.io/libs-release' }
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.8'
}
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:pgsql.properties" })
@ComponentScan(basePackages = {"com.example.persistence"})
public class PersistenceConfig
{
    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource()
    {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory()
    {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.example.persistence.domain" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public HibernateTransactionManager transactionManager()
    {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory().getObject());
        return txManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation()
    {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties hibernateProperties() {
        return new Properties() {
            {
                setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
                setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
                setProperty("hibernate.globally_quoted_identifiers", "true");
            }
        };
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceConfig.class})
public class ProductServiceTest
{
    private static final Logger LOG = LoggerFactory.getLogger(ProductServiceTest.class);

    @Autowired
    private ProductService productService;

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public final void listApplicationBeans() throws Exception
    {
        List<String> beans = Arrays.asList(applicationContext.getBeanDefinitionNames());
        for (String bean: beans)
        {
            LOG.info(String.format("--> App Beans [%s]", bean));
        }
    }
}
# jdbc
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://some_address:5432/some_database
jdbc.user=someuser
jdbc.pass=somepassword

# hibernate
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
@Entity
public class Product implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String name;

    public long getId()
    {
        return id;
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Product(String name)
    {
        setName(name);
    }

    @Override
    public String toString()
    {
        StringBuilder builder = new StringBuilder();

        builder.append(Product.class.getSimpleName()).append(" [\n");
        builder.append("id = ").append(id).append("\n");
        builder.append("name = ").append(name).append("\n");
        builder.append("]");

        return builder.toString();
    }

}
import org.springframework.stereotype.Repository;
import com.example.persistence.dao.common.AbstractDao;
import com.example.persistence.domain.Product;
@Repository
public class ProductDao extends AbstractDao<Product>
{
    public ProductDao()
    {
        super();
        setClazz(Product.class);
    }
}
@Service
public class ProductService extends AbstractService<Product>
{
    @Autowired
    private ProductDao dao;

    public ProductService()
    {
        super();
    }

    @Override
    protected IOperation<Product> getDao()
    {
        return dao;
    }
}

根据堆栈跟踪:

Could not autowire field: private com.example.persistence.dao.impl.ProductDao
com.example.persistence.service.impl.ProductService.dao; nested exception is 
org.springframework.beans.factory.NoSuchBeanDefinitionException:
当我发现这样的问题时,我消除了以下内容:

  • 该bean未被注释或未被组件扫描覆盖。 你定义 @ComponentScan(basePackages={“com.example.persistence”})
    它涵盖了您的包com.example.persistence.dao.impl.ProductDao
    看,这里很好
  • 确保注释正确:ProductDao在@Repository中注释
    看起来不错
  • 确保com.example.persistence.dao.impl.ProductDao位于类路径中。 您正在执行命令gradle clean test,这意味着您的代码将在测试执行之前进行编译(因为测试取决于编译任务)。
    如果它编译了,我猜ProductDao在您的类路径中
  • 确保JUnit具有引导所需的配置 spring应用程序上下文。
    @上下文配置
    类指向您的配置类。 未定义加载器属性,因此spring将使用默认的DelegatingSmartContextLoader(配置中没有@WebAppConfiguration,版本>3.2)。
    我觉得不错
  • 不幸的是,我找不到任何问题,一切看起来都很好(我希望此检查表将帮助某人)。
    所以我猜这个问题是在缺少细节的地方;比如,您必须在不同的包下对ProductDao进行分类,并且您在ProductService中使用了错误的一个,或者使用了错误的接口等等


    希望这有帮助

    我在测试套件中遇到了与Spring Hibernate项目类似的问题

    我能解决这个问题的唯一方法是通过使用它的超类作为它的类型(在你的例子中是
    AbstractService
    )来自动连接这个类,然后使用
    @限定符告诉Spring我指的是哪个子类。在您的案例中,它将看起来像这样:

    @Qualifier("ProductService")
    @Autowired
    private AbstractService productService;
    

    这很痛苦,因为在测试函数中,每次使用属于子类的方法时,都必须将
    productService
    对象转换为
    productService
    。因此,如果您已经使用其他解决方案解决了此问题,请与我们共享

    我与您分享一个Hibernate java配置示例。 我希望你喜欢它:

    前置要求:pom.xml

        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <spring.version>4.0.6.RELEASE</spring.version>
        </properties>
    
        <dependencies>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>commons-dbcp</groupId>
                <artifactId>commons-dbcp</artifactId>
                <version>1.2.2</version>
            </dependency>
    
            <dependency>
                <groupId>javax.persistence</groupId>
                <artifactId>persistence-api</artifactId>
                <version>1.0</version>
            </dependency>
    
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>4.1.9.Final</version>
            </dependency>
    
            <!-- POSTGRESQL -->
            <dependency>
                <groupId>postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <version>9.1-901-1.jdbc4</version>
            </dependency>
    
        </dependencies>
    
    步骤2:Config.java

    package com.curso.online;
    
    import java.util.Properties;
    
    import javax.sql.DataSource;
    
    import org.apache.commons.dbcp.BasicDataSource;
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.context.annotation.PropertySources;
    import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
    import org.springframework.orm.hibernate4.HibernateTransactionManager;
    import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    @Configuration
    @EnableTransactionManagement
    @PropertySources(value = { @PropertySource("classpath:/application.properties") })
    @ComponentScan(basePackages = "com.curso.online")
    public class Config {
    
        @Value("${jdbc.driverClassName}")
        private String KEY_DRIVER_CLASS;
    
        @Value("${jdbc.url}")
        private String KEY_JDBC_URL;
    
        @Value("${jdbc.username}")
        private String KEY_JDBC_USERNAME;
    
        @Value("${jdbc.password}")
        private String KEY_JDBC_PASSWORD;
    
        @Value("${hibernate.dialect}")
        private String KEY_HIBERNATE_DIALECT;
    
        @Value("${hibernate.show_sql}")
        private String KEY_HBERNATE_SHOW_SQL;
    
        @Value("${packagesToScan}")
        private String KEY_ENTITIES_PKG;
    
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    
        @Bean
        public LocalSessionFactoryBean sessionFactory() {
            LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
            factory.setDataSource(dataSource());
            factory.setPackagesToScan(KEY_ENTITIES_PKG);
            factory.setHibernateProperties(hibernateProperties());
            return factory;
        }
    
        public Properties hibernateProperties() {
            Properties properties = new Properties();
            properties.setProperty("hibernate.dialect", KEY_HIBERNATE_DIALECT);
            properties.setProperty("hibernate.show_sql", KEY_HBERNATE_SHOW_SQL);
            return properties;
        }
    
        @Bean
        @Autowired
        public HibernateTransactionManager transactionManager(
                SessionFactory sessionFactory) {
            return new HibernateTransactionManager(sessionFactory);
        }
    
        @Bean
        public DataSource dataSource() {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(KEY_DRIVER_CLASS);
            dataSource.setUrl(KEY_JDBC_URL);
            dataSource.setUsername(KEY_JDBC_USERNAME);
            dataSource.setPassword(KEY_JDBC_PASSWORD);
            return dataSource;
        }
    
    }
    

    我无法重现你的问题。你确定你的
    ProductDao
    类是用
    @Repository
    注释的吗?