Spring 對象的獲取,以及數據庫連接應用


1.Spring IOC反射機制,需要調用無參構造器

springioc編寫規則:接收方注入,需要定義set方法或帶參的構造器

//利用反射創建對象(無參構造器),利用反射機制注入參數

<bean id="calss="">

  <property name="" value|ref=""></property>

</bean>

使用BasicDataSource進行數據庫連接,數據庫連接連接池,不用考慮創建,與釋放連接。實現了DataSource接口

<bean id="dbcp" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="username" value="root"></property>
    <property name="password" value="123456"></property>
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/tracy"></property>
</bean>

 

//原理利用反射機制創建對象,調用帶參構造器

<bean id="calss="">

  <constructor-arg index=""  value|ref=""/>

</bean>

Spring對Jdbc進行了封裝,JdbcTemplate依賴於DataSource

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <constructor-arg index="0"  ref="dbcp"></constructor-arg>
</bean>

一般使用BeanPropertyRowMapper實現類。可以完成數據到JavaBean的自動封裝

new BeanPropertyRowMapper<類型>(類型.class)

2.Spring 注解標記的使用,用注解標記獲取數據

 a.創建實體類

public class FanNews implements Serializable {

	public int id;
	public String fan_item;
	public String fan_name;
	

  

b.創建接口

public interface FanNewsDao {
    
    public List<FanNews> loadAll();

}

 

c.創建接口實現類並進行注解標志的添加 一般注解標記默認id是首字母小寫,注解標記可以省略set方法

@Repository("fanNewsDao")
public class JdbcTemplateFanNews implements FanNewsDao {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
        public List<FanNews> loadAll() {
    
         String sql="select *from fan_news";
         
          List<FanNews> list=jdbcTemplate.query(sql,new BeanPropertyRowMapper<FanNews>(FanNews.class));
          
          for(FanNews news:list) {
          System.out.println(news.getFan_name()+news.getFan_item()); 
          }
        return list;
    }

}

 

d.在xml開啟組件掃描

<!-- 開啟組件掃描可以識別以下標記  @Contorller @Service @Repository @Component@Resource @Autowired-->
<!-- 開啟組件掃描  @Contorller @Service @Repository @Component@Resource @Autowired-->
 <context:component-scan base-package="com.tracy.dao.impl" />

 

e.在test類中進行測試 一般獲取接口對象,靈活性比較高  獲取的對象為接口對象,不是實現類。

@Test 
      public void TestNewDao() {
      
          String config="com/tracy/xml/applicationContext.xml"; 
      ApplicationContext acc=new  ClassPathXmlApplicationContext(config); 

      FanNewsDao fnd=acc.getBean("fanNewsDao",JdbcTemplateFanNews.class);
      List<FanNews> list=fnd.loadAll(); 
      System.out.println(list); 
      
      for(FanNews news:list) {
      System.out.println("注解標記讀取接口"+news.getFan_name()+news.getFan_item()); 
      } 
      }

f.讀取的結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM