2014-02-20 101 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; 
    } 

}