2014-02-20 100 views
0

我已经使用Spring Framework工作了几个工程,并且我在application-context.xml及其与数据库的关系中遇到了一些问题。如何用.java文件替换aplication-context.xml

我解决了使用Hibernate

不过,我想这些问题,知道我怎么能有一个java文件替换xml文件,就像我曾与web.xml中

package com.test.spring.config; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.web.servlet.config.annotation.EnableWebMvc; 
import org.springframework.web.servlet.view.JstlView; 
import org.springframework.web.servlet.view.UrlBasedViewResolver; 

@Configuration //Marks this class as configuration 
//Specifies which package to scan 

@ComponentScan("com.test.spring") 
//Enables Spring's annotations 

@EnableWebMvc 
public class Config { 
    @Bean 
    public UrlBasedViewResolver setupViewResolver() { 
     UrlBasedViewResolver resolver = new UrlBasedViewResolver(); 
     resolver.setPrefix("/WEB-INF/views/"); 
     resolver.setSuffix(".jsp"); 
     resolver.setViewClass(JstlView.class); 
     return resolver; 
    } 
} 

做这是我的应用程序-context.xml

<?xml version="1.0" encoding="ISO-8859-1"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:p="http://www.springframework.org/schema/p" 
     xmlns:aop="http://www.springframework.org/schema/aop" 
     xmlns:tx="http://www.springframework.org/schema/tx" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"> 


    <bean id="dataSource" 
      class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
     <property name="url" value="jdbc:mysql://localhost:3306/database" /> 
     <property name="username" value="root"/> 
     <property name="password" value="00000"/> 
    </bean> 
</beans> 

回答

1

事情是这样的:

@Configuration 
public class ContextConfiguration { 

    @Bean 
    public DataSource dataSource() { 
     final DriverManagerDataSource ds = new DriverManagerDataSource(); 
     ds.setDriverClassName("com.mysql.jdbc.Driver"); 
     ds.setUrl("jdbc:mysql://localhost:3306/database"); 
     ds.setUsername("root"); 
     ds.setPassword("00000"); 
     return ds; 
    } 

}