2013-07-25 17 views
27

jak na sprężynę documentation, etapy użyć Wiosna JdbcTemplate następująco:pomocą wiosna JdbcTemplate - wstrzyknięcie źródła danych vs jdbcTemplate

<?xml version="1.0" encoding="UTF-8"?> 
    <beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xsi:schemaLocation=" 
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

     <!-- Scans within the base package of the application for @Components to configure as beans --> 
     <context:component-scan base-package="org.springframework.docs.test" /> 

     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 
      <property name="driverClassName" value="${jdbc.driverClassName}"/> 
      <property name="url" value="${jdbc.url}"/> 
      <property name="username" value="${jdbc.username}"/> 
      <property name="password" value="${jdbc.password}"/> 
     </bean> 

     <context:property-placeholder location="jdbc.properties"/> 

    </beans> 

a następnie

@Repository 
    public class JdbcCorporateEventDao implements CorporateEventDao { 

     private JdbcTemplate jdbcTemplate; 

     @Autowired 
     public void setDataSource(DataSource dataSource) { 
      this.jdbcTemplate = new JdbcTemplate(dataSource); 
     } 

     // JDBC-backed implementations of the methods on the CorporateEventDao follow... 
    } 

Zasadniczo JdbcTemplate tworzony wewnątrz klasy Component za pomocą ustawiacza dla źródła danych.

Czy jest coś złego w zrobieniu tego w ten sposób, aby w aplikacji było dokładnie JEDNO wystąpienie jdbcTemplate?

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" 
    p:dataSource-ref="dataSource" 
/> 

, a następnie wstrzyknięcie samego jdbcTemplate bezpośrednio do składnika

@Repository 
public class JdbcCorporateEventDao implements CorporateEventDao { 
    @Resource("jdbcTemplate") 
    private JdbcTemplate jdbcTemplate; 


    // JDBC-backed implementations of the methods on the CorporateEventDao follow... 
} 

Czy istnieje powód, dlaczego sama jdbcTemplate nie musi być wstrzykiwany do klasy komponentów bezpośrednio?

SGB

+0

może być duplikatem http: // stackoverflo w.com/q/9460507/309399. Ale na to pytanie nie ma odpowiedzi. – SGB

Odpowiedz

24

Możesz zrobić, co chcesz. The javadoc of JdbcTemplate nawet wyraźnie mówi:

Może być stosowany w realizacji usług poprzez bezpośrednie odniesienie instancji z DataSource, lub przygotować się w kontekście aplikacji i usług podane jako odniesienie do fasoli.

+2

++ dla łącza. Dzięki za zwięzłą odpowiedź i cytat z javadoc. To pytanie od jakiegoś czasu mnie dręczy - wszystkie przykłady, które widziałem w Internecie wydają się wstrzykiwać źródło danych - sprawiając, że zastanawiam się, czy czegoś brakuje ... – SGB

21

W wiosenno-context.xml dodać następujące i

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 
    <property name="dataSource" ref="dataSource"/> 
</bean> 

i bezpośrednio można użyć jdbcTemplate przez autowiring jak

@Autowired JdbcTemplate jdbcTemplate; 

przykład:

this.jdbcTemplate.query("select * from ******",new RowMapper()); 
+0

Jak zrobić to samo dla wielu źródeł danych? Czy mogę określić tak: i dla innego źródła danych, np. . Czy to jest właściwy sposób ustawiania wielu źródeł danych na szablonie JDBC – Analysts

+0

@Analysts, Powinieneś zdefiniować osobny plik jdbcTemplate dla każdego źródła danych, więc jeśli masz 2 źródła danych, będziesz miał jdbcTemplate1 dla datasource1 i jdbcTemplate2 dla datasource2 i wstrzyknij jdbcTemplates osobno w razie potrzeby do poziomu warstwy usługi – SGB

+0

To, co powiedział @SCB, jest poprawne, musisz mieć wiele komponentów dla wielu baz danych. – Odaiah

5

You może to również zrobić tak, jak

@Configuration 
@Import({PersistenceConfig.class}) 
@ComponentScan(basePackageClasses = { 
    ServiceMarker.class, 
    RepositoryMarker.class } 
) 
public class AppConfig { 

    /** 
    * To resolve ${} in @Values, you must register a static PropertySourcesPlaceholderConfigurer in either XML or 
    * annotation configuration file. 
    */ 
    @Bean 
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { 
     return new PropertySourcesPlaceholderConfigurer(); 
    } 
} 

PersistenceConfig

@Configuration 
@PropertySource(value = { "classpath:database/jdbc.properties" }) 
@EnableTransactionManagement 
public class PersistenceConfig { 

    @Autowired 
    private Environment env; 

/** 
    * The @Bean annotation is used to declare a Spring bean and the DI requirements. The @Bean annotation is equivalent to 
* the <bean> tag, the method name is equivalent to the id attribute within the <bean> tag. 
    * 
    * <bean id="mySqlDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close" 
     p:driverClassName="${jdbc.mysql.driverClassName}" 
     p:url="${jdbc.mysql.url}" 
     p:username="${jdbc.mysql.username}" 
     p:password="${jdbc.mysql.password}" /> 
    * 
    * @return 
    */ 
    @Bean(destroyMethod = "close") 
    public DataSource mySqlDataSource() { 
     BasicDataSource dataSource = new BasicDataSource(); 
     dataSource.setDriverClassName(env.getProperty("jdbc.mysql.driverClassName")); 
     dataSource.setUrl(env.getProperty("jdbc.mysql.url")); 
     dataSource.setUsername(env.getProperty("jdbc.mysql.username")); 
     dataSource.setPassword(env.getProperty("jdbc.mysql.password")); 
     return dataSource; 
    } 

    @Bean(destroyMethod = "close") 
    public DataSource ls360DataSource() { 
     BasicDataSource dataSource = new BasicDataSource(); 
     dataSource.setDriverClassName(env.getProperty("jdbc.ls360.driverClassName")); 
     dataSource.setUrl(env.getProperty("jdbc.ls360.url")); 
     dataSource.setUsername(env.getProperty("jdbc.ls360.username")); 
     dataSource.setPassword(env.getProperty("jdbc.ls360.password")); 
     return dataSource; 
    } 
} 

MySqlDaoImpl

@Repository 
public class MySqlDaoImpl implements MySqlDao{ 

    private static final Logger logger = LogManager.getLogger(); 

    @Inject 
    private DataSource mySqlDataSource; 
    private JdbcTemplate mySqlJdbcTemplate; 

    @PostConstruct 
    public void afterPropertiesSet() throws Exception { 
     if (mySqlDataSource == null) { 
      throw new BeanCreationException("Must set mySqlDataSource on " + this.getClass().getName()); 
     } 
     this.mySqlJdbcTemplate = new JdbcTemplate(mySqlDataSource); 
    } 

    @Override 
    public void callStoredProcedure(String storedProcedureName, Map<String, Object> inParamMap) throws Exception { 

     SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(mySqlJdbcTemplate).withProcedureName(storedProcedureName); 
     SqlParameterSource in = new MapSqlParameterSource(inParamMap); 

     logger.info("Calling stored Procedure: " + storedProcedureName); 
     Map<String, Object> simpleJdbcCallResult = simpleJdbcCall.execute(in); 
     logger.info("Stored Procedure Result: " + simpleJdbcCallResult); 
    } 
} 

główna

public static void main(String[] args) { 
    try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) { 
     MySQLDao mySqlDao = springContext.getBean(MySQLDaoImpl.class); 
     try { 
      Map<String, Object> inParamMap = new HashMap<String, Object>(); 
      inParamMap.put("iCourseId", 1); 
      mySqlCourseRenewalDao.callStoredProcedure("usp_processCourseRenewal", inParamMap); 
     } catch (Exception e) { 
      logger.error("Exception occurs", e); 
     } 
    } catch (Exception e) { 
     logger.error("Exception occurs in loading Spring context: ", e); 
    } 
} 

Dzięki

Powiązane problemy