• 工作中遇到的问题--实现CustomerSetting的实时更新


    首先在项目运行时就初始化CustomerSettings的值,采用@Bean,默认是singtone模式,只会加载一次。

    @Configuration
    @Order(3)
    @EnableWebMvcSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class MFGWebSecurityConfigurerAdapter extends
            AWebSecurityConfigurerAdapter {

        @Autowired
        private UserRepository userRepository;

        @Autowired
        private CustomerSettingsRepository customerSettingsRepository;

        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity
                    .formLogin()
                    .successHandler(
                            new SavedRequestAwareAuthenticationSuccessHandler())
                    .loginPage("/login").permitAll().failureUrl("/login-error")
                    .defaultSuccessUrl("/").and().logout()
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/logged-out").permitAll().and().rememberMe()
                    .key(SECURITY_TOKEN)
                    .tokenRepository(persistentTokenRepository())
                    .tokenValiditySeconds(mfgSettings.getRememberMeTokenValidity())
                    .and().sessionManagement().maximumSessions(1)
                    .sessionRegistry(sessionRegistry).and().sessionFixation()
                    .migrateSession().and().authorizeRequests().anyRequest()
                    .authenticated();
        }

        @Bean
        public PersistentTokenRepository persistentTokenRepository() {
            JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
            tokenRepository.setDataSource(dataSource);
            return tokenRepository;
        }

        @Bean
        @LoggedInUser
        @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
        @Transactional(readOnly = true)
        public User getLoggedInUser() {
            Authentication authentication = SecurityContextHolder.getContext()
                    .getAuthentication();
            if (authentication != null
                    && !(authentication instanceof AnonymousAuthenticationToken)
                    && authentication.isAuthenticated())
                return userRepository.findByLogin(authentication.getName());
            return null;
        }

        @Bean
        @SystemUser
        @Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.NO)
        @Transactional(readOnly = true)
        public User getSystemUser() {
            return userRepository.findByLogin(Constants.SYSTEM_USER);
        }

        @Bean
        public CustomerSettings customerSettings() {
            return customerSettingsRepository.findAll().get(0);
        }
    }
    为了能够在CustomerSettings发生改变时,对相关的值进行实时更新,在CustomerService中添加更新后的操作方法:

        @Override
        protected void afterUpdate(CustomerSettings t) {
            customerSettings.editFrom(t);
        }

        @Override
        protected void afterEdit(CustomerSettings t) {
            customerSettings.editFrom(t);
        }

    另外:enitForm方法是写在CustomerSettings.java这个实体类中的,这样在更新时就能实现对其中元素的部分更新,避免以前实训中有些元素没更新就会被置空,需要每次都先查询再手动部分更新的情况。

    以下是这个实体中使用enitForm的案例:

    package com.sim.mfg.data.domain;

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Date;
    import java.util.List;
    import java.util.Set;

    import javax.persistence.Column;
    import javax.persistence.EntityListeners;
    import javax.persistence.FetchType;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    import javax.persistence.MappedSuperclass;
    import javax.persistence.Transient;
    import javax.persistence.Version;

    import org.springframework.data.annotation.CreatedBy;
    import org.springframework.data.annotation.CreatedDate;
    import org.springframework.data.annotation.LastModifiedBy;
    import org.springframework.data.annotation.LastModifiedDate;
    import org.springframework.data.jpa.domain.support.AuditingEntityListener;

    import com.fasterxml.jackson.annotation.JsonIgnore;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.sim.mfg.data.dto.Action;

    /**
     * AMfgObject, based of all MFG data classes
     * @author system-in-motion
     *
     */
    @MappedSuperclass
    @EntityListeners({AuditingEntityListener.class})
    public abstract class AMfgObject {
        
        @Version
        @Column(name = "VERSION")
        private int version;

        @CreatedDate
        @Column(name = "CREATION_DATE", nullable = false)
        private Date creationDate;
        
        @LastModifiedDate
        @Column(name = "UPDATE_DATE")
        private Date updateDate;
        
        @JsonIgnore
        @CreatedBy
        @JoinColumn(name = "CREATED_BY", nullable = false)
        @ManyToOne(fetch = FetchType.LAZY)
        private User createdBy;
        
        @JsonIgnore
        @LastModifiedBy
        @JoinColumn(name = "UPDATED_BY")
        @ManyToOne(optional = true, fetch = FetchType.LAZY)
        private User updatedBy;
        
        @Column(name = "ENABLED", columnDefinition = "INT", nullable = false)
        private boolean enabled = true;
        
        @Transient
        private Set<Action> actions;

        /**
         * Empty constructor
         */
        public AMfgObject() {}    
        /**
         * Override this method to provide object edition from another object
         * @param <T>
         * @param dto
         * @return
         */
        public abstract void editFrom(AMfgObject object);
        
        public int getVersion() {
            return version;
        }
        public void setVersion(int version) {
            this.version = version;
        }
        public Date getCreationDate() {
            return creationDate;
        }

        public void setCreationDate(Date creationDate) {
            this.creationDate = creationDate;
        }

        public Date getUpdateDate() {
            return updateDate;
        }

        public void setUpdateDate(Date updateDate) {
            this.updateDate = updateDate;
        }

        public User getCreatedBy() {
            return createdBy;
        }

        public void setCreatedBy(User createdBy) {
            this.createdBy = createdBy;
        }

        public User getUpdatedBy() {
            return updatedBy;
        }

        public void setUpdatedBy(User updatedBy) {
            this.updatedBy = updatedBy;
        }

        public boolean isEnabled() {
            return enabled;
        }

        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }
        
        @JsonProperty
        public Set<Action> getActions() {
            return actions;
        }

        public void setActions(Set<Action> actions) {
            this.actions = actions;
        }
        
        /**
         * Return a list of arrays of action data to be displayed by DataTables
         * @return
         */
        public List<String[]> getActionArrays() {
            List<String[]> actionArrays = new ArrayList<String[]>();
            if (actions != null) {
                for (Action action : actions) {
                    actionArrays.add(new String[] {
                            action.getBase(),
                            action.getAction(),
                            action.getStyle(),
                            action.getIcon(),
                            action.getAltText(),
                            action.getObjectId() == null ? "" : String.valueOf(action.getObjectId())});
                }
            }
            // Sort by base + action to make sure the order is the same on each row
            Collections.sort(actionArrays, new Comparator<String[]>() {
                private static final int BASE = 0;
                private static final int ACTION = 1;
                @Override
                public int compare(String[] arg0, String[] arg1) {
                    return (arg0[BASE]+arg0[ACTION]).compareTo(arg1[BASE]+arg1[ACTION]);
                }
                
            });
            return actionArrays;
        }
        
    }

    package com.sim.mfg.data.domain;

    import java.io.Serializable;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;

    import org.hibernate.annotations.Where;
    import org.hibernate.validator.constraints.NotBlank;

    import com.sim.mfg.data.domain.type.DistributionOperationType;

    @Entity
    @Table(name = "CUSTOMERSETTINGS")
    @Where(clause = "enabled=1")
    public class CustomerSettings extends AMfgObject implements Serializable{

        /**
         *
         */
        private static final long serialVersionUID = 559748589762162346L;
        
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        
        @NotBlank
        @Column(name = "NAME", nullable = false)
        private String name;

        @Column(name = "PREFIXLOWER", nullable = false)
        private String prefixLower;

        @Column(name = "PREFIXUPPER", nullable = false)
        private String prefixUpper;
        
        @Column(name = "CODEURL", nullable = false)
        private String codeUrl;

        @Column(name = "BATCHEXPIRYTIMEOUT", nullable = false)
        private long batchExpiryTimeout;
        
        @Column(name = "PRODUCTIONDATEENABLED", nullable = false)
        private boolean productionDateEnabled = true;

        @Column(name = "EXPIRYDATEENABLED", nullable = false)
        private boolean expiryDateEnabled = true;

        @Column(name = "FILLLOCATIONWIDGETENABLED", nullable = false)
        private boolean fillLocationWidgetEnabled = true;

        @Column(name = "PRODUCTSHELFLIFEENABLED", nullable = false)
        private boolean productShelfLifeEnabled = true;

        @Column(name = "PRODUCTBARCODEENABLED", nullable = false)
        private boolean productBarcodeEnabled = true;

        @Column(name = "WEIXINTOKEN", nullable = false)
        private String weixinToken;

        @Column(name = "WEIXINCORPID", nullable = false)
        private String weixinCorpId;

        @Column(name = "WEIXINENCODINGAESKEY", nullable = false)
        private String weixinEncodingAesKey;

        @Column(name = "WEIXINCORPSECRET", nullable = false)
        private String weixinCorpSecret;

        @Column(name = "WEIXINCODEAPPLICATIONAPPID", nullable = false)
        private Integer weixinCodeApplicationAppId;

        @Column(name = "WEIXINSHIPMENTOPERATIONAPPID", nullable = false)
        private Integer weixinShipmentOperationAppId;

        @Column(name = "WEIXINDELIVERYOPERATIONAPPID", nullable = false)
        private Integer weixinDeliveryOperationAppId;

        @Column(name = "WEIXINRECEPTIONOPERATIONAPPID", nullable = false)
        private Integer weixinReceptionOperationAppId;

        @Column(name = "WEIXINSIMPLERECEPTIONOPERATIONAPPID", nullable = false)
        private Integer weixinSimpleReceptionOperationAppId;

        @Column(name = "WEIXINRETURNOPERATIONAPPID", nullable = false)
        private Integer weixinReturnOperationAppId;

        @Column(name = "WEIXININVENTORYOPERATIONAPPID", nullable = false)
        private Integer weixinInventoryOperationAppId;

        @Column(name = "WEIXINMOVEMENTOPERATIONAPPID", nullable = false)
        private Integer weixinMovementOperationAppId;

        @Column(name = "WEIXINFILLINGOPERATIONAPPID", nullable = false)
        private Integer weixinFillingOperationAppId;
        /**
         * Empty constructor
         */
        public CustomerSettings() {    }
        
        /**
         * Get Weixin app id for given distribution operation type
         * @param operationType
         * @return
         */
        public Integer getWeixinDistributionOperationAppId(DistributionOperationType operationType) {
            switch (operationType) {
            case SHIPMENT:
                return weixinShipmentOperationAppId;
            case DELIVERY:
                return weixinDeliveryOperationAppId;
            case RECEPTION:
                return weixinReceptionOperationAppId;
            case RETURN:
                return weixinReturnOperationAppId;
            case INVENTORY:
                return weixinInventoryOperationAppId;
            case SIMPLERECEPTION:
                return weixinSimpleReceptionOperationAppId;
            default:
                return null;
            }
        }

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPrefixLower() {
            return prefixLower;
        }

        public void setPrefixLower(String prefixLower) {
            this.prefixLower = prefixLower;
        }

        public String getPrefixUpper() {
            return prefixUpper;
        }

        public void setPrefixUpper(String prefixUpper) {
            this.prefixUpper = prefixUpper;
        }

        public String getCodeUrl() {
            return codeUrl;
        }

        public void setCodeUrl(String codeUrl) {
            this.codeUrl = codeUrl;
        }

        public long getBatchExpiryTimeout() {
            return batchExpiryTimeout;
        }

        public void setBatchExpiryTimeout(long batchExpiryTimeout) {
            this.batchExpiryTimeout = batchExpiryTimeout;
        }

        public boolean isProductionDateEnabled() {
            return productionDateEnabled;
        }

        public void setProductionDateEnabled(boolean productionDateEnabled) {
            this.productionDateEnabled = productionDateEnabled;
        }

        public boolean isExpiryDateEnabled() {
            return expiryDateEnabled;
        }

        public void setExpiryDateEnabled(boolean expiryDateEnabled) {
            this.expiryDateEnabled = expiryDateEnabled;
        }

        public boolean isFillLocationWidgetEnabled() {
            return fillLocationWidgetEnabled;
        }

        public void setFillLocationWidgetEnabled(boolean fillLocationWidgetEnabled) {
            this.fillLocationWidgetEnabled = fillLocationWidgetEnabled;
        }

        public boolean isProductShelfLifeEnabled() {
            return productShelfLifeEnabled;
        }

        public void setProductShelfLifeEnabled(boolean productShelfLifeEnabled) {
            this.productShelfLifeEnabled = productShelfLifeEnabled;
        }

        public boolean isProductBarcodeEnabled() {
            return productBarcodeEnabled;
        }

        public void setProductBarcodeEnabled(boolean productBarcodeEnabled) {
            this.productBarcodeEnabled = productBarcodeEnabled;
        }

        public String getWeixinToken() {
            return weixinToken;
        }

        public void setWeixinToken(String weixinToken) {
            this.weixinToken = weixinToken;
        }

        public String getWeixinCorpId() {
            return weixinCorpId;
        }

        public void setWeixinCorpId(String weixinCorpId) {
            this.weixinCorpId = weixinCorpId;
        }

        public String getWeixinEncodingAesKey() {
            return weixinEncodingAesKey;
        }

        public void setWeixinEncodingAesKey(String weixinEncodingAesKey) {
            this.weixinEncodingAesKey = weixinEncodingAesKey;
        }

        public String getWeixinCorpSecret() {
            return weixinCorpSecret;
        }

        public void setWeixinCorpSecret(String weixinCorpSecret) {
            this.weixinCorpSecret = weixinCorpSecret;
        }

        public Integer getWeixinCodeApplicationAppId() {
            return weixinCodeApplicationAppId;
        }

        public void setWeixinCodeApplicationAppId(Integer weixinCodeApplicationAppId) {
            this.weixinCodeApplicationAppId = weixinCodeApplicationAppId;
        }

        public Integer getWeixinShipmentOperationAppId() {
            return weixinShipmentOperationAppId;
        }

        public void setWeixinShipmentOperationAppId(Integer weixinShipmentOperationAppId) {
            this.weixinShipmentOperationAppId = weixinShipmentOperationAppId;
        }

        public Integer getWeixinDeliveryOperationAppId() {
            return weixinDeliveryOperationAppId;
        }

        public void setWeixinDeliveryOperationAppId(Integer weixinDeliveryOperationAppId) {
            this.weixinDeliveryOperationAppId = weixinDeliveryOperationAppId;
        }

        public Integer getWeixinReceptionOperationAppId() {
            return weixinReceptionOperationAppId;
        }

        public void setWeixinReceptionOperationAppId(
                Integer weixinReceptionOperationAppId) {
            this.weixinReceptionOperationAppId = weixinReceptionOperationAppId;
        }

        public Integer getWeixinSimpleReceptionOperationAppId() {
            return weixinSimpleReceptionOperationAppId;
        }

        public void setWeixinSimpleReceptionOperationAppId(
                Integer weixinSimpleReceptionOperationAppId) {
            this.weixinSimpleReceptionOperationAppId = weixinSimpleReceptionOperationAppId;
        }

        public Integer getWeixinReturnOperationAppId() {
            return weixinReturnOperationAppId;
        }

        public void setWeixinReturnOperationAppId(Integer weixinReturnOperationAppId) {
            this.weixinReturnOperationAppId = weixinReturnOperationAppId;
        }

        public Integer getWeixinInventoryOperationAppId() {
            return weixinInventoryOperationAppId;
        }

        public void setWeixinInventoryOperationAppId(
                Integer weixinInventoryOperationAppId) {
            this.weixinInventoryOperationAppId = weixinInventoryOperationAppId;
        }

        public Integer getWeixinMovementOperationAppId() {
            return weixinMovementOperationAppId;
        }

        public void setWeixinMovementOperationAppId(Integer weixinMovementOperationAppId) {
            this.weixinMovementOperationAppId = weixinMovementOperationAppId;
        }

        public Integer getWeixinFillingOperationAppId() {
            return weixinFillingOperationAppId;
        }

        public void setWeixinFillingOperationAppId(Integer weixinFillingOperationAppId) {
            this.weixinFillingOperationAppId = weixinFillingOperationAppId;
        }

        @Override
        public void editFrom(AMfgObject object) {
            if(object==null)
                return ;
            CustomerSettings custSettings=(CustomerSettings)object;
            this.name=custSettings.getName();
            this.codeUrl=custSettings.getCodeUrl();
            this.batchExpiryTimeout=custSettings.getBatchExpiryTimeout();
            this.expiryDateEnabled=custSettings.isExpiryDateEnabled();
            this.fillLocationWidgetEnabled=custSettings.isFillLocationWidgetEnabled();
            this.prefixLower=custSettings.getPrefixLower();
            this.prefixUpper=custSettings.getPrefixUpper();
            this.productBarcodeEnabled=custSettings.isProductBarcodeEnabled();
            this.productionDateEnabled=custSettings.isProductionDateEnabled();
            this.productShelfLifeEnabled=custSettings.isProductShelfLifeEnabled();
            this.weixinCodeApplicationAppId=custSettings.getWeixinCodeApplicationAppId();
            this.weixinCorpId=custSettings.getWeixinCorpId();
            this.weixinCorpSecret=custSettings.getWeixinCorpSecret();
            this.weixinDeliveryOperationAppId=custSettings.getWeixinDeliveryOperationAppId();
            this.weixinEncodingAesKey=custSettings.getWeixinEncodingAesKey();
            this.weixinFillingOperationAppId=custSettings.getWeixinFillingOperationAppId();
            this.weixinInventoryOperationAppId=custSettings.getWeixinInventoryOperationAppId();
            this.weixinMovementOperationAppId=custSettings.getWeixinMovementOperationAppId();
            this.weixinReceptionOperationAppId=custSettings.getWeixinReceptionOperationAppId();
            this.weixinReturnOperationAppId=custSettings.getWeixinReturnOperationAppId();
            this.weixinShipmentOperationAppId=custSettings.getWeixinShipmentOperationAppId();
            this.weixinSimpleReceptionOperationAppId=custSettings.getWeixinSimpleReceptionOperationAppId();
            this.weixinToken=custSettings.getWeixinToken();
        }

        @Override
        public String toString() {
            return "CustSettings [id=" + id + ", name=" + name + ", codeUrl="
                    + codeUrl + "]";
        }
        
    }

  • 相关阅读:
    【转】忘记密码功能的安全实现(邮件方式)
    windows7下安装gem包---bcrypt-ruby
    Ruby中的%表示法
    ruby中特殊的全局变量
    rails中一个窗体多个模型——fields_for
    【转】深刻理解render 和 redirect_to
    UML核心元素--分析类
    UML核心元素--包
    UML核心元素--边界
    UML核心元素--用例
  • 原文地址:https://www.cnblogs.com/ly-radiata/p/4789666.html
Copyright © 2020-2023  润新知