Spring+Mybatis基於註解整合Redis

来源:http://www.cnblogs.com/Revel-sl/archive/2016/09/05/5841861.html
-Advertisement-
Play Games

基於這段時間折騰redis遇到了各種問題,想著整理一下。本文主要介紹基於Spring+Mybatis以註解的形式整合Redis。廢話少說,進入正題。 首先準備Redis,我下的是Windows版,下載後直接啟動redis-server就行了,見下圖: 一,先上jar包 二,創建實體類 三,dao介面 ...


  基於這段時間折騰redis遇到了各種問題,想著整理一下。本文主要介紹基於Spring+Mybatis以註解的形式整合Redis。廢話少說,進入正題。

  首先準備Redis,我下的是Windows版,下載後直接啟動redis-server就行了,見下圖:

  

一,先上jar包

  

二,創建實體類     

 1 package com.sl.user.vo;
 2 
 3 import java.io.Serializable;
 4 
 5 import com.fasterxml.jackson.databind.PropertyNamingStrategy;
 6 import com.fasterxml.jackson.databind.annotation.JsonNaming;
 7 import com.fasterxml.jackson.databind.annotation.JsonSerialize;
 8 
 9 @JsonSerialize  
10 @JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)  
11 public class UserVO implements Serializable{
12 
13     private static final long serialVersionUID = 1L;
14     
15     private int id;
16     private String username;
17     private String password;
18     private int age;
19     
20     public UserVO(){
21         super(); 
22     }
23     
24     public UserVO(int id, String username, String password, int age) {
25         super();
26         this.id = id;
27         this.username = username;
28         this.password = password;
29         this.age = age;
30     }
31 
32     public int getId() {
33         return id;
34     }
35 
36     public void setId(int id) {
37         this.id = id;
38     }
39 
40     public String getUsername() {
41         return username;
42     }
43 
44     public void setUsername(String username) {
45         this.username = username;
46     }
47 
48     public String getPassword() {
49         return password;
50     }
51 
52     public void setPassword(String password) {
53         this.password = password;
54     }
55 
56     public int getAge() {
57         return age;
58     }
59 
60     public void setAge(int age) {
61         this.age = age;
62     }
63 
64     @Override
65     public String toString() {
66         return "UserVO [id=" + id + ", username=" + username + ", password="
67                 + password + ", age=" + age + "]";
68     }
69 
70 }

三,dao介面

 1 package com.sl.user.dao;
 2 
 3 import com.sl.user.vo.UserVO;
 4 
 5 public interface UserDao {
 6     
 7     public void addUser(UserVO user);
 8     
 9     public void deleteUser(UserVO user);
10     
11     public void updateUser(UserVO user);
12     
13     public UserVO getUserById(int id);
14     
15     public UserVO getUser(int id);
16     
17 }

四,UserMapper

 1 <?xml version="1.0" encoding="UTF-8" ?>  
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  
 3 <mapper namespace="com.sl.user.dao.UserDao" >
 4     
 5     <resultMap id="userResult" type="User">
 6         <result column="id" property="id"/>
 7         <result column="userame" property="userame"/>
 8         <result column="password" property="password"/>
 9         <result column="age" property="age"/>
10     </resultMap>
11     
12     <insert id="addUser" parameterType="User">
13         insert into t_user(username,password,age) values(#{username},#{password},#{age})
14     </insert>
15     
16     <update id="deleteUser" parameterType="User">
17         delete * from t_user where id = #{id}
18     </update>
19     
20     <update id="updateUser" parameterType="User">
21         update t_user set
22         <if test="username != null and username != ''"> username = #{username},</if>
23         <if test="password != null and password != ''"> password = #{password},</if>
24         <if test="age != null and age != ''"> age = #{age}</if>
25         where 1=1
26         <if test="id != null and id != ''">and id = #{id}</if>
27         
28     </update>
29     
30     <select id="getUser" parameterType="int" resultType="User" >
31         select * from t_user where id = #{id}
32     </select>
33     
34     <select id="getUserById" parameterType="int" resultType="java.lang.String" >
35         select username from t_user where id = #{id}
36     </select>
37     
38 </mapper>  

五,Service介面

 1 package com.sl.user.service;
 2 
 3 import com.sl.user.vo.UserVO;
 4 
 5     public interface UserService {
 6     
 7         public void addUser(UserVO user);
 8         
 9         public void deleteUser(UserVO user);
10         
11         public void updateUser(UserVO user);
12         
13         public UserVO getUserById(int id);
14         
15         public UserVO getUser(int id);
16     
17 }

六,Service實現

 1 package com.sl.user.service.impl;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.cache.annotation.CacheEvict;
 5 import org.springframework.cache.annotation.Cacheable;
 6 import org.springframework.stereotype.Service;
 7 import org.springframework.transaction.annotation.Propagation;
 8 import org.springframework.transaction.annotation.Transactional;
 9 
10 import com.sl.user.dao.UserDao;
11 import com.sl.user.service.UserService;
12 import com.sl.user.vo.UserVO;
13 
14 @Service("userService")
15 @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
16 public class UserServiceImpl implements UserService{
17     
18     @Autowired
19     private UserDao userDao;
20     
21     @Override
22     @CacheEvict(value="User",key="addUser",allEntries=true) 
23     public void addUser(UserVO user) {
24         userDao.addUser(user);
25     }
26 
27     @Override
28     @CacheEvict(value = {"getUser", "getUserById"}, allEntries = true)  
29     public void deleteUser(UserVO user) {
30         userDao.deleteUser(user);
31     }
32 
33     @Override
34     @CacheEvict(value = {"getUser", "getUserById"}, allEntries = true)  
35     public void updateUser(UserVO user) {
36         userDao.updateUser(user);
37     }
38 
39     @Override
40     @Cacheable(value="User",key="getUserById")
41     public UserVO getUserById(int id) {
42         return userDao.getUserById(id);
43     }
44     
45     @Override
46     @Cacheable(value="User",key="'getUser'")
47     public UserVO getUser(int id) {
48         return userDao.getUser(id);
49     }
50 
51 }

七,Ctrl層

 1 package com.sl.user.web;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Controller;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.ResponseBody;
10 
11 import com.sl.user.service.UserService;
12 import com.sl.user.vo.UserVO;
13 
14 @Controller
15 @RequestMapping("/userCtrl")
16 public class UserCtrl {
17     
18     @Autowired
19     private UserService userService;
20     
21     @RequestMapping("/addUser")
22     public void addUser(UserVO user){
23         userService.addUser(user);
24     }
25     
26     @RequestMapping("/deleteUser")
27     public void deleteUser(UserVO user){
28         userService.deleteUser(user);
29     }
30     
31     @RequestMapping("/updateUser")
32     public void updateUser(UserVO user){
33         userService.updateUser(user);
34     }
35     
36     @ResponseBody
37     @RequestMapping("/getUserById")
38     public Map<String,Object> getUserById(UserVO user){
39         Map<String,Object> map = new HashMap<String,Object>();
40         map.put("msg",userService.getUserById(4));
41         return map;
42     }
43     
44     @ResponseBody
45     @RequestMapping("/getUser")
46     public Map<String,Object> getUser(UserVO vo){
47         Map<String,Object> map = new HashMap<String,Object>();
48         Object user = userService.getUser(4);
49         map.put("msg",user.toString());
50         return map;
51     }
52     
53 }

八,Redis關鍵類,用於CRUD操作

  1 package com.sl.user.redis;
  2 import java.io.ByteArrayInputStream;  
  3 import java.io.ByteArrayOutputStream;  
  4 import java.io.IOException;  
  5 import java.io.ObjectInputStream;  
  6 import java.io.ObjectOutputStream;  
  7   
  8 import org.springframework.cache.Cache;  
  9 import org.springframework.cache.support.SimpleValueWrapper;  
 10 import org.springframework.dao.DataAccessException;  
 11 import org.springframework.data.redis.connection.RedisConnection;  
 12 import org.springframework.data.redis.core.RedisCallback;  
 13 import org.springframework.data.redis.core.RedisTemplate;
 14 
 15 public class RedisUtil implements Cache{
 16     
 17     private RedisTemplate<String, Object> redisTemplate;    
 18     private String name;    
 19     public RedisTemplate<String, Object> getRedisTemplate() {  
 20         return redisTemplate;    
 21     }  
 22        
 23     public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {  
 24         this.redisTemplate = redisTemplate;    
 25     }  
 26        
 27     public void setName(String name) {  
 28         this.name = name;    
 29     }  
 30        
 31     @Override    
 32     public String getName() {  
 33         return this.name;    
 34     }  
 35   
 36     @Override    
 37     public Object getNativeCache() {  
 38         return this.redisTemplate;    
 39     }  
 40     
 41     /**
 42      * 從緩存中獲取key
 43      */
 44     @Override    
 45     public ValueWrapper get(Object key) {  
 46 System.out.println("get key");  
 47       final String keyf =  key.toString();  
 48       Object object = null;  
 49       object = redisTemplate.execute(new RedisCallback<Object>() {  
 50       public Object doInRedis(RedisConnection connection)    
 51                   throws DataAccessException {  
 52           byte[] key = keyf.getBytes();  
 53           byte[] value = connection.get(key);  
 54           if (value == null) {  
 55              return null;  
 56             }  
 57           return toObject(value);  
 58           }  
 59        });  
 60         return (object != null ? new SimpleValueWrapper(object) : null);  
 61       }  
 62     
 63      /**
 64       * 將一個新的key保存到緩存中
 65       * 先拿到需要緩存key名稱和對象,然後將其轉成ByteArray
 66       */
 67      @Override    
 68      public void put(Object key, Object value) {  
 69 System.out.println("put key");  
 70        final String keyf = key.toString();    
 71        final Object valuef = value;    
 72        final long liveTime = 86400;    
 73        redisTemplate.execute(new RedisCallback<Long>() {    
 74            public Long doInRedis(RedisConnection connection)    
 75                    throws DataAccessException {    
 76                 byte[] keyb = keyf.getBytes();    
 77                 byte[] valueb = toByteArray(valuef);    
 78                 connection.set(keyb, valueb);    
 79                 if (liveTime > 0) {    
 80                     connection.expire(keyb, liveTime);    
 81                  }    
 82                 return 1L;    
 83              }    
 84          });    
 85       }  
 86   
 87       private byte[] toByteArray(Object obj) {    
 88          byte[] bytes = null;    
 89          ByteArrayOutputStream bos = new ByteArrayOutputStream();    
 90          try {    
 91            ObjectOutputStream oos = new ObjectOutputStream(bos);    
 92            oos.writeObject(obj);    
 93            oos.flush();    
 94            bytes = bos.toByteArray();    
 95            oos.close();    
 96            bos.close();    
 97           }catch (IOException ex) {    
 98                ex.printStackTrace();    
 99           }    
100           return bytes;    
101         }    
102   
103        private Object toObject(byte[] bytes) {  
104          Object obj = null;    
105            try {  
106                ByteArrayInputStream bis = new ByteArrayInputStream(bytes);    
107                ObjectInputStream ois = new ObjectInputStream(bis);    
108                obj = ois.readObject();    
109                ois.close();    
110                bis.close();    
111            } catch (IOException ex) {    
112                ex.printStackTrace();    
113             } catch (ClassNotFoundException ex) {    
114                ex.printStackTrace();    
115             }    
116             return obj;    
117         }  
118        
119        /**
120         * 刪除key
121         */
122        @Override    
123        public void evict(Object key) {    
124 System.out.println("del key");  
125          final String keyf = key.toString();    
126          redisTemplate.execute(new RedisCallback<Long>() {    
127          public Long doInRedis(RedisConnection connection)    
128                    throws DataAccessException {    
129              return connection.del(keyf.getBytes());    
130             }    
131           });    
132         }  
133        
134         /**
135          * 清空key
136          */
137         @Override    
138         public void clear() {    
139 System.out.println("clear key");  
140            redisTemplate.execute(new RedisCallback<String>() {    
141                 public String doInRedis(RedisConnection connection)    
142                         throws DataAccessException {    
143                   connection.flushDb();    
144                     return "ok";    
145                }    
146            });    
147         }  
148   
149         @Override  
150         public <T> T get(Object key, Class<T> type) {  
151             return null;  
152         }  
153       
154         @Override  
155         public ValueWrapper putIfAbsent(Object key, Object value) {  
156             return null;  
157         }  
158       
159 }

九,Spring整合mybatis和redis配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:context="http://www.springframework.org/schema/context" 
 6     xmlns:tx="http://www.springframework.org/schema/tx"
 7     xmlns:mvc="http://www.springframework.org/schema/mvc"
 8     xmlns:aop="http://www.springframework.org/schema/aop"
 9     xmlns:cache="http://www.springframework.org/schema/cache"
10     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
11        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
12        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
13        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
14        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
15        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
16     
17     <!-- 掃描dao,service -->
18     <context:component-scan base-package="com.sl.user.service" />
19     <context:component-scan base-package="com.sl.user.service.*" />
20     <context:component-scan base-package="com.sl.user.redis" />
21     <!-- 啟用註解 -->
22     <context:annotation-config/>
23     <!-- 啟動緩存註解 -->
24     <cache:annotation-driven/>
25     
26     <!-- MyBatis start -->
27         <!-- 配置dataSource DriverManagerDataSource-->
28         <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
29             <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
30             <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property>
31             <property name="username" value="root"></property>
32             <property name="password" value="root"></property>
33         </bean>
34     
35         <!-- MyBatis配置 SqlSessionFactoryBean -->
36         <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
37             <property name="dataSource" ref="dataSource"></property>
38             <property name="configLocation" value="classpath:config/mybatis.xml"></property>
39             <property name="mapperLocations" value="classpath:mapper/UserMapper.xml"></property>
40         </bean>
41         
42         <!-- mybatis自動掃描載入Sql映射文件/介面 : MapperScannerConfigurer 
43                    sqlSessionFactory
44                 basePackage:指定sql映射文件/介面所在的包(自動掃描) -->
45         <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
46             <property name="sqlSessionFactory" ref="sessionFactory"></property>
47             <property name="basePackage" value="com.sl.user.dao"></property>
48         </bean>
49                 
50          <!-- 事務管理  DataSourceTransactionManager-->
51          <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
52              <property name="dataSource" ref="dataSource"></property>
53          </bean>
54          
55          <!-- 使用聲明式事務 transaction-manager:引用上面定義的事務管理器-->
56          <tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven>
57          
58      <!-- MyBatis end -->
59      
60      <!-- 配置redis部分 start -->
61      
62          <!-- 配置redis連接池  JedisPoolConfig-->
63          <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
64              <property name="maxIdle" value="300" />  
65             <property name="maxTotal" value="600" />  
66          </bean> 
67          
68          <!-- 配置CoonnectionFactory JedisConnectionFactory-->
69          <bean id="connFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
70               <property name="hostName" value="127.0.0.1"></property>
71               <property name="port" value="6379"></property>
72               <property name="poolConfig" ref="poolConfig"></property>
73          </bean>
74         
75          <!-- 配置redisTemplate StringRedisTemplate-->
76          <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
77             <property name="connectionFactory" ref="connFactory"/>
78          </bean>
79          
80          <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">    
81              <property name="caches">    
82                 <set>    
83                     <bean class="com.sl.user.redis.RedisUtil">    
84                          <property name="redisTemplate" ref="redisTemplate" />    
85                          <property name="name" value="User"/>    
86                          <!-- User名稱要在類或方法的註解中使用 -->  
87                     </bean>  
88                 </set>    
89              </property>    
90          </bean>
91 
92 </beans>

十,SpringMVC配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <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"
 3     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
 6        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
 7        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
 8        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
 9        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
10 
11     <mvc:annotation-driven/>
12     <!-- 啟用spring mvc 註解 -->
13     <context:annotation-config/>
14     <!-- 設置使用註解的類所在的jar包 -->
15     <context:component-scan base-package="com.sl.user.*"></context:component-scan>
16 
17     <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前尾碼 -->
18     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
19         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
20         <property name="prefix" value="/views/"/>
21         <property name="suffix" value=".jsp"/>
22     </bean>
23 
24     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
25         <!-- JSON轉換器 -->
26         <property name="messageConverters">
27             <list>
28                 <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
29                     <property name="supportedMediaTypes">
30                         <list>
31                             <value>application/json;charset=utf-8</value>
32                             <value>text/json;charset=utf-8</value>
33                         </list>
34                     </property>
35                 </bean>
36             </list>
37         </property>
38     </bean>
39 
40 </beans>

十一,mybatis配置文件

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Blocks理解: Blocks可以訪問局部變數,但是不能修改 如果修改局部變數,需要加__block 2、如果局部變數是數組或者指針的時候只複製這個指針,兩個指針指向同一個地址,block只修改指針上的內容。如: 例子裡面確實沒有修改mArrayCount這個局部變數啊。mArrayCount是一 ...
  • 開始Java的學習,從Android,開始吧。《第一代碼》開始閱讀和調試demo例子。 下麵是 《第一行代碼》的思維導圖: ...
  • 本文主要介紹Android中從Gallery獲取圖片 設計項目佈局 打開packages\apps\Gallery下的清單文件,可以看到其中包含下麵的代碼: 邏輯部分代碼如下: ...
  • 基於 HDP2.4安裝(五):集群及組件安裝 創建的hadoop集群,修改預設配置,將hbase 存儲配置為 Azure Blob Storage 目錄: 簡述 配置 驗證 簡述: hadoop-azure 提供hadoop 與 azure blob storage 集成支持,需要部署 hadoop ...
  • 基於linux 創建HDInsight HBase集群,選擇最小配置,zk(3)、NN(2)、WN(2),集群節點預設組件服務規劃如下 NN0: Active NameNode /HDFS ZKFailoverController/HDFS App Timeline Server /YARN Act ...
  • 使用Saprk SQL 操作Hive的數據 前提準備: 1、啟動Hdfs,hive的數據存儲在hdfs中; 2、啟動hive -service metastore,元數據存儲在遠端,可以遠程訪問; 3、在spark的conf目錄下增加hive-site.xml配置文件,文件內容: 編寫Scala測試 ...
  • 1 begin 2 3 declare @i int ; 4 5 set @i=77541214; 6 7 update dbo.test set code='AMHD'+CONVERT(varchar,@i),@i=@i+1; 8 9 end ...
  • 《原創,僅供學習交流》 在關聯規則的研究中,有很多串列的演算法,經典的是Apriori演算法和FP_growth演算法。也有很多並行演算法, 如CD( count distribution ) 、DD ( data distribution ) 、CaD( candidate distribution)、F ...
一周排行
    -Advertisement-
    Play Games
  • 通過WPF的按鈕、文本輸入框實現了一個簡單的SpinBox數字輸入用戶組件並可以通過數據綁定數值和步長。本文中介紹了通過Xaml代碼實現自定義組件的佈局,依賴屬性的定義和使用等知識點。 ...
  • 以前,我看到一個朋友在對一個系統做初始化的時候,通過一組魔幻般的按鍵,調出來一個隱藏的系統設置界面,這個界面在常規的菜單或者工具欄是看不到的,因為它是一個後臺設置的關鍵界面,不公開,同時避免常規用戶的誤操作,它是作為一個超級管理員的入口功能,這個是很不錯的思路。其實Winform做這樣的處理也是很容... ...
  • 一:背景 1. 講故事 前些天有位朋友找到我,說他的程式每次關閉時就會自動崩潰,一直找不到原因讓我幫忙看一下怎麼回事,這位朋友應該是第二次找我了,分析了下 dump 還是挺經典的,拿出來給大家分享一下吧。 二:WinDbg 分析 1. 為什麼會崩潰 找崩潰原因比較簡單,用 !analyze -v 命 ...
  • 在一些報表模塊中,需要我們根據用戶操作的名稱,來動態根據人員姓名,更新報表的簽名圖片,也就是電子手寫簽名效果,本篇隨筆介紹一下使用FastReport報表動態更新人員簽名圖片。 ...
  • 最新內容優先發佈於個人博客:小虎技術分享站,隨後逐步搬運到博客園。 創作不易,如果覺得有用請在Github上為博主點亮一顆小星星吧! 博主開始學習編程於11年前,年少時還只會使用cin 和cout ,給單片機點點燈。那時候,類似async/await 和future/promise 模型的認知還不是 ...
  • 之前在阿裡雲ECS 99元/年的活動實例上搭建了一個測試用的MINIO服務,以前都是直接當基礎設施來使用的,這次準備自己學一下S3相容API相關的對象存儲開發,因此有了這個小工具。目前僅包含上傳功能,後續計劃開發一個類似圖床的對象存儲應用。 ...
  • 目錄簡介快速入門安裝 NuGet 包實體類User資料庫類DbFactory增刪改查InsertSelectUpdateDelete總結 簡介 NPoco 是 PetaPoco 的一個分支,具有一些額外的功能,截至現在 github 星數 839。NPoco 中文資料沒多少,我是被博客園群友推薦的, ...
  • 前言 前面使用 Admin.Core 的代碼生成器生成了通用代碼生成器的基礎模塊 分組,模板,項目,項目模型,項目欄位的基礎功能,本篇繼續完善,實現最核心的模板生成功能,並提供生成預覽及代碼文件壓縮下載 準備 首先清楚幾個模塊的關係,如何使用,簡單畫一個流程圖 前面完成了基礎的模板組,模板管理,項目 ...
  • 假設需要實現一個圖標和文本結合的按鈕 ,普通做法是 直接重寫該按鈕的模板; 如果想作為通用的呢? 兩種做法: 附加屬性 自定義控制項 推薦使用附加屬性的形式 第一種:附加屬性 創建Button的附加屬性 ButtonExtensions 1 public static class ButtonExte ...
  • 在C#中,委托是一種引用類型的數據類型,允許我們封裝方法的引用。通過使用委托,我們可以將方法作為參數傳遞給其他方法,或者將多個方法組合在一起,從而實現更靈活的編程模式。委托類似於函數指針,但提供了類型安全和垃圾回收等現代語言特性。 基本概念 定義委托 定義委托需要指定它所代表的方法的原型,包括返回類 ...