spring如何处理有自定义final属性的注入情况? 10C

通常spring的注入模式都是单例的,并通过set方法注入依赖,但是,如果用spring管理的对象,
如果拥有一些属性值,且这些属性值是final的,必须在对象new出来时定义并赋值,且这些值并非固定的,是随着环境变化的,该怎么办呢,比如我用spring管理一个thread类,这个线程类执行的时候需要两个int参数,这个时候该如何办?

1个回答

通过构造函数注入参数,参数可以通过配置文件设置,spring读取配置文件的值然后注入。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Spring factoryBean加载 框架内部嵌套加载问题
各位大神,最近在研究spring框架bean加载过程,遇到一个棘手问题,我相信研究spring原理的大神肯定对这个问题有兴趣 我的项目框架是spring+rpc,配置文件方式注入bean,非注解 一部分bean是普通的serivce bean配置,spring内部走正常bean的加载过程,没有问题; 还有一部分是自定义标签,通过一个工厂类生成service的代理对象bean,作为消费者/生产者,这个工厂类实现了FactoryBean接口,spring内部走FactoryBean的加载过程 public class RemoteServiceFactory implements FactoryBean<Object>, BeanFactoryAware, InitializingBean { private static final Logger log = LoggerFactory.getLogger(RemoteServiceFactory.class);  public RemoteServiceFactory(Object bean, String path, int port) {   this.object = bean; // 自定义标签中配置的service bean的引用(ref属性,引用配置文件bean id)   this.path = path; // 生产者服务路径(和此问题无关)   this.port = port; // 生产者服务端口(和此问题无关)  }    public boolean isSingleton() {   return true;  }  public void afterPropertiesSet() throws Exception {    // 根据this.object创建相应的生产者/消费者代理对象,用于rpc  } } 问题分析,debug spring bean解析后的加载过程 1.spring对配置文件解析后,遍历所有的bean,进行一一实例化   AbstractApplicationContext:finishBeanFactoryInitialization()     内部调用beanFactory.preInstantiateSingletons();       DefaultListableBeanFactory:preInstantiateSingletons()         内部遍历beanNames,进行一一实例化 2.假如第一个bean是普通的service bean,在初始化时,会解析内部的依赖,然后遍历依赖参数,解析依赖   DefaultListableBeanFactory:doResolveDependency()     内部调用findAutowireCandidates()        内部调用BeanFactoryUtils.beanNamesForTypeIncludingAncestors()         内部调用lbf.getBeanNamesForType()           -> DefaultListableBeanFactory:doGetBeanNamesForType()   关键就在这里,doGetBeanNamesForType方法内部会遍历所有bean,去判断是否匹配上面的依赖参数的类型,   当遍历到实现FactoryBean的bean时,会实例化这个bean(因为FactoryBean只是代理,不是真正bean),然后又会解析factoryBean中真实bean中的依赖参数,   然后就又会走到这里,导致一直嵌套下去的加载过程   如果程序加载没有问题,则一切正常;一旦某个类加载失败(比如某个类注入的属性在properties中不存在),就会出现大量的异常信息抛出,   原因就是上面的嵌套加载,某个类加载抛出异常会一直抛出到嵌套的最顶层,每一层的异常信息都会积攒下来,最后爆发似的抛出   (每层的异常信息都是 当前这层bean的加载失败) 各位大神:   我一直感觉spring这样嵌套加载在设计上是不应该的,不理解为什么会这样,单纯匹配类型的话,不能通过其他方式获取FactoryBean中真实bean的类型吗?     为什么非要实例化它呢?有什么方法可以解决这个问题?
quartz 集群环境下,停掉一个点,该点下的定时任务不被其他点承接,定时任务不再执行
集群环境下 springboot + quartz,停掉一个点,该点下的定时任务不被其他点承接,定时任务不再执行 两个job类20秒执行一次 0/20 * * * * ? 启动两个,能看到控制台的两个项目分别打印两个定时任务的日志,停掉其中一个项目,日志不变,停掉项目中的任务没有被运行的项目执行,运行的项目还执行原任务 配置文件 ``` #quartz集群配置 # =========================================================================== # Configure Main Scheduler Properties 调度器属性 # =========================================================================== #调度标识名 集群中每一个实例都必须使用相同的名称 org.quartz.scheduler.instanceName=DefaultQuartzScheduler #ID设置为自动获取 每一个必须不同 org.quartz.scheduler.instanceid=AUTO #============================================================================ # Configure ThreadPool #============================================================================ #线程池的实现类(一般使用SimpleThreadPool即可满足几乎所有用户的需求) org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool #指定线程数,至少为1(无默认值)(一般设置为1-100直接的整数合适) org.quartz.threadPool.threadCount=10 #设置线程的优先级(最大为java.lang.Thread.MAX_PRIORITY 10,最小为Thread.MIN_PRIORITY 1,默认为5) org.quartz.threadPool.threadPriority=5 #============================================================================ # Configure JobStore #============================================================================ # 信息保存时间 默认值60秒 org.quartz.jobStore.misfireThreshold=60000 #数据保存方式为数据库持久化 org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX #数据库代理类,一般org.quartz.impl.jdbcjobstore.StdJDBCDelegate可以满足大部分数据库 org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate #JobDataMaps是否都为String类型 org.quartz.jobStore.useProperties=false #数据库别名 随便取 org.quartz.jobStore.dataSource=myDS #表的前缀,默认QRTZ_ org.quartz.jobStore.tablePrefix=QRTZ_ #是否加入集群 org.quartz.jobStore.isClustered=true #调度实例失效的检查时间间隔 org.quartz.jobStore.clusterCheckinInterval=15000 ``` ``` @Configuration public class QuartzConfiguration { @Autowired DataSource dataSource; /** * 继承org.springframework.scheduling.quartz.SpringBeanJobFactory 实现任务实例化方式 */ public static class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { private transient AutowireCapableBeanFactory beanFactory; @Override public void setApplicationContext(final ApplicationContext context) { beanFactory = context.getAutowireCapableBeanFactory(); } /** * 将job实例交给spring ioc托管 我们在job实例实现类内可以直接使用spring注入的调用被spring ioc管理的实例 * * @param bundle * @return * @throws Exception */ @Override protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception { final Object job = super.createJobInstance(bundle); /** * 将job实例交付给spring ioc */ beanFactory.autowireBean(job); return job; } } /** * 配置任务工厂实例 * * @param applicationContext spring上下文实例 * @return */ @Bean public JobFactory jobFactory(ApplicationContext applicationContext) { /** * 采用自定义任务工厂 整合spring实例来完成构建任务 see {@link AutowiringSpringBeanJobFactory} */ AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory(); jobFactory.setApplicationContext(applicationContext); return jobFactory; } /** * 配置任务调度器 使用项目数据源作为quartz数据源 * * @param jobFactory 自定义配置任务工厂 * @return * @throws Exception */ @Bean(destroyMethod = "destroy", autowire = Autowire.NO) public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory) throws Exception { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); // 将spring管理job自定义工厂交由调度器维护 schedulerFactoryBean.setJobFactory(jobFactory); // 设置覆盖已存在的任务 schedulerFactoryBean.setOverwriteExistingJobs(true); // 项目启动完成后,等待10秒后开始执行调度器初始化 schedulerFactoryBean.setStartupDelay(10); // 设置调度器自动运行 schedulerFactoryBean.setAutoStartup(true); // 设置数据源,使用与项目统一数据源 schedulerFactoryBean.setDataSource(dataSource); // 设置上下文spring bean name schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContext"); // 设置配置文件位置 schedulerFactoryBean.setConfigLocation(new ClassPathResource("/application-quartz.properties")); return schedulerFactoryBean; } } ```
Spring FactoryBean的使用
我碰到一个比较纳闷的问题: 我定义了一个类为: Java code /** * AcegiCacheManagerFactoryBean 负责初始化缓存后生成AcegiCacheManager * 调用 authenticationService 来获取资源和用户实例,并加入UserCache 和 ResourceCache 中 * @author zhanghg * */ public class AcegiCacheManagerFactoryBean implements FactoryBean,InitializingBean { protected final Log logger = LogFactory.getLog(getClass()); private AcegiCacheManager acegiCacheManager; private AuthenticationService authenticationService; private UserCache userCache; private ResourceCache resourceCache; public Object getObject() throws Exception { return this.acegiCacheManager; } @SuppressWarnings("unchecked") public Class getObjectType() { return (this.acegiCacheManager != null ? this.acegiCacheManager.getClass() : AcegiCacheManager.class); } public boolean isSingleton() { return true; } public void afterPropertiesSet() throws Exception { logger.info("Initializing SecurityCacheManager"); Assert.notNull(userCache,"userCache should not be null"); Assert.notNull(resourceCache,"resourceCache should not be null"); Assert.notNull(authenticationService,"Authentication Service should not be null"); //初始化缓存 List<Staff> users =authenticationService.getUsers(); for (Iterator iter = users.iterator(); iter.hasNext();) { UserDetails user = (UserDetails) iter.next(); userCache.putUserInCache(user); } List<Resource> rescs =authenticationService.getResources(); for (Iterator iter = rescs.iterator(); iter.hasNext();) { Resource resc = (Resource) iter.next(); resourceCache.putResourceInCache(resc); } //生成 acegiCacheManager this.acegiCacheManager = new AcegiCacheManager(userCache,resourceCache); } //-------------setters----------- public void setAcegiCacheManager(AcegiCacheManager acegiCacheManager) { this.acegiCacheManager = acegiCacheManager; } @Required public void setAuthenticationService(AuthenticationService authenticationService) { this.authenticationService = authenticationService; } @Required public void setUserCache(UserCache userCache) { this.userCache = userCache; } @Required public void setResourceCache(ResourceCache resourceCache) { this.resourceCache = resourceCache; } } 同时还定义了一个类为: [code=Java] /** * AcegiCacheManager是对缓存进行统一管理,以屏蔽其它类对缓存的直接操作 * 对缓存中的用户和资源进行初始化、增、删、改、清空等操作 * @author zhanghg * */ public class AcegiCacheManager { private UserCache userCache; private ResourceCache resourceCache; //rescTypeMapp 映射资源类型对应的资源的一对多关系,以便快速查找。 //如method类型对应哪些资源实例,url资源类型对应哪些资源实例 private Map<String,List<String>> rescTypeMapping; //-----constructor using fields @SuppressWarnings("unchecked") public AcegiCacheManager(UserCache userCache, ResourceCache resourceCache) { System.out.println("实例化SecurityManager"); this.userCache = userCache; this.resourceCache = resourceCache; // 获取所有的资源,以初始化 rescTypeMapping rescTypeMapping = new HashMap<String,List<String>>(); List<String> resclist = resourceCache.getAllResources(); for (Iterator iter = resclist.iterator(); iter.hasNext();) { String resString = (String) iter.next(); System.out.println("初始化SecurityCacheManager时取得资源信息的path:"+resString); ResourceDetails resc = resourceCache.getResourceFromCache(resString); System.out.println("输出该资源的type类型为:"+resc.getResourceType()); List<String> typelist = rescTypeMapping.get(resc.getResourceType()); if(typelist==null){ typelist = new ArrayList<String>(); rescTypeMapping.put(resc.getResourceType(), typelist); } typelist.add(resString); } System.out.println("输出最终的resTypeMapping信息:"+rescTypeMapping.size()); } //-----get from cache methods public UserDetails getUser(String username) { return userCache.getUserFromCache(username); } public ResourceDetails getResourceFromCache(String resString) { return resourceCache.getResourceFromCache(resString); } //-----remove from cache methods public void removeUser(String username){ userCache.removeUserFromCache(username); } public void removeResource(String resString){ ResourceDetails rd = resourceCache.getResourceFromCache(resString); List<String> typelist = rescTypeMapping.get(rd.getResourceType()); typelist.remove(resString); resourceCache.removeResourceFromCache(resString); } //------add to cache methods public void addUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, GrantedAuthority[] authorities){ User user = new User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); addUser(user); } public void addUser(UserDetails user){ System.out.println("进来,添加user至缓存"); userCache.putUserInCache(user); } public void addResource(String resourceName,String resString, String resType, GrantedAuthority[] authorities){ Resource rd = new Resource(resourceName,resString, resType, authorities); addResource(rd); } public void addResource(ResourceDetails rd){ List<String> typelist = rescTypeMapping.get(rd.getResourceType()); if(typelist==null){ typelist = new ArrayList<String>(); rescTypeMapping.put(rd.getResourceType(), typelist); } typelist.add(rd.getPath()); resourceCache.putResourceInCache(rd); } // ------renovate cache methods public void renovateUser(String orgUsername, String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, GrantedAuthority[] authorities){ removeUser(orgUsername); addUser(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); } public void renovateUser(String orgUsername, UserDetails user){ removeUser(orgUsername); addUser(user); } public void renovateResource(String resName,String orgResString,String resString, String resType, GrantedAuthority[] authorities ){ removeResource(orgResString); addResource(resName,resString, resType, authorities); } public void renovateResource(String orgResString,ResourceDetails rd){ removeResource(orgResString); addResource(rd); } //-------getters and setters------------------- public void clearResources() { rescTypeMapping = new HashMap<String,List<String>>(); resourceCache.removeAllResources(); } public void setResourceCache(ResourceCache resourceCache) { this.resourceCache = resourceCache; } public void setUserCache(UserCache userCache) { this.userCache = userCache; } /** * 根据资源类型,在rescTypeMapping职工获取所有该类型资源的对应的resource string * @param resType * @return List */ public List<String> getResourcesByType(String resType) { return rescTypeMapping.get(resType); } /** * 获取所有资源的对应的resource string * @return */ public List<String> getAllResources(){ return resourceCache.getAllResources(); } /** * 获取所有用户实例对应的user name * @return */ @SuppressWarnings("unchecked") public List<String> getAllUsers(){ EhCacheBasedUserCache ehUserCache = (EhCacheBasedUserCache)userCache; return ehUserCache.getCache().getKeys(); } } [/code] 同时我的一个类:StaffManager中要用到AcegiCacheManager类 public class StaffManager { // 统一定义所有HQL private static final String QUERY_ADMIN_HQL = "select staff from Staff staff join staff.roles as role where role.roleName=?"; private final Logger logger = LoggerFactory.getLogger(StaffManager.class); //自动装配该bean的属性 @Autowired private StaffDao staffDao; @Autowired private RoleDao roleDao; @Autowired private PrivilegeDao privilegeDao; @Autowired private ResourceDao resourceDao; private AcegiCacheManager acegiCacheManager; 通过@Reqiured进行了注解. 其中我在配置文件配置了bean: <beans:bean id="acegiCacheManager" class="com.sdcncsi.security.cache.manager.AcegiCacheManagerFactoryBean" > 但是为什么staffManager当中,取到的acegiCacheManager老是null呢? 当然通过上下文的getBean("acegiCacheManager")是可以取到这个类的,不是null [b]问题补充:[/b] 楼上的还还是不明白: 如果通过在xml文件中注册bean: <beans:bean id="acegiCacheManager" class="com.sdcncsi.security.cache.manager.AcegiCacheManagerFactoryBean" > 那么我应该在staffManager中怎样写才能取得不为null啊? 而如果我通过@Component("acegiCacheManager")进行注解, 我在staffManager中进行@Autowired,但是为什么提示: Could not autowire field: private com.sdcncsi.security.cache.manager.AcegiCacheManager,com.sdcncsi.service.sys.StaffManager注解错误? 我该 怎样做? 另外factory bean会在服务启动时自动的启动这个bean吗? 而AcegiCacheManager是在AcegiCacheManagerFactoryBean中使用的,但是如果在其它类中我们怎样来引用它,直接注入AcegiCacheManager吗?但是这个类没有默认构造方法,不能实例化. 我现在都晕了,搞的好头大,请各位大人帮忙啊. [b]问题补充:[/b] lovewhzlq说通过这样改定就可以: ------------------------------------------------------------- @Autowired private ResourceDao resourceDao; @Autowired private AcegiCacheManager acegiCacheManager; ----------------------------------------------------------- 我试了后不行: 1)我的配置文件中配置了: <beans:bean id="acegiCacheManager" class="com.sdcncsi.security.cache.manager.AcegiCacheManagerFactoryBean" > 它 是指向工厂类的,这样在启动的时候可以初始化信息. 后来,我把AcegiCacheManagerFactoryBean进行了@Component("acegiCacheManager") 并且在StaffManager中对 AcegiCacheManager acegiCacheManager 启用@Autowired, 提示:Could not autowire field: rror creating bean with name 'acegiCacheManager': FactoryBean which is currently in creation returned null from getObject 我该如何做才对啊?
在spring管理的类如何在运行时取得泛型的类型
使用hibernate+spring写的一个BaseDaoSupport。 我的做法是定义一个IBaseDaoSupport接口,该接口里面定义了一些公共的操作数据方法. 提供了两种实现方式,一个是按照hibernate自己的实现方式,一个是继承了spring的hibernateDaoSupport,并提供了自己的实现方法.这两个方法都要实现IBaseDaoSupport接口,然后有一个BaseDaoSupport类,该类也要实现IBaseDaoSupport接口,并在里面定义IBaseDaoSupport 类型的成员属性而且提供getter和setter方法,用来在spring中注入到底需要的是那种实现方式. package com.clear.dao; import java.io.Serializable; import java.util.List; /** * 该接口用于实现基本的数据操作 * @author Administrator * */ public interface IBaseDaoSupport<K extends Serializable, T> { /** * 该方法用于添加一个实体 * @param entity * @return */ public Boolean isSaveEntity(T entity); /** * 该方法用于修改一个实体 * @param entity * @return */ public Boolean isUpdateEntity(T entity); /** * 该方法用于删除一个实体 * @param id * @return */ public Boolean isDeleteEntity(K id); /** * 根据ID查询一个实体 * @param id * @return */ public T findEntityById(K id); /** * 查询所有 * @return */ public List<T> findEntityAll(); /** * 根据查询语句和参数查询 * @param ql * @param params * @return */ public List<T> findEntityByQueryLanguage(String queryString, Object... params); public List<T> findEntityBySQLQuery(String sql,Object... params); } package com.clear.dao; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.sql.SQLException; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.clear.pojo.Trade; /** * 该类用于实现Spring支持下的数据操作方式 * * @author Yanwei * * @param <K> * ID的泛型 * @param <T> * 实体的泛型 */ public class BaseDaoSupportBySpring<K extends Serializable, T> extends HibernateDaoSupport implements IBaseDaoSupport<K, T> { @SuppressWarnings("unchecked") public List<T> findEntityAll() { return getHibernateTemplate().loadAll(entityClass()); } @SuppressWarnings("unchecked") public T findEntityById(K id) { return (T) getHibernateTemplate().get(entityClass(), id); } @SuppressWarnings("unchecked") public List<T> findEntityByQueryLanguage(String queryString, Object... params) { return getHibernateTemplate().find(queryString, params); } public Boolean isDeleteEntity(K id) { Boolean flag = false; try { T entity = findEntityById(id); getHibernateTemplate().delete(entity); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } public Boolean isSaveEntity(T entity) { Boolean flag = false; try { getHibernateTemplate().save(entity); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } public Boolean isUpdateEntity(T entity) { Boolean flag = false; try { getHibernateTemplate().update(entity); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } //用于拿到运行时泛型的类型 @SuppressWarnings("unchecked") public Class<T> entityClass() { return (Class<T>) ((ParameterizedType) BaseDaoSupportBySpring.class .getGenericSuperclass()).getActualTypeArguments()[1]; } @SuppressWarnings("unchecked") public List<T> findEntityBySQLQuery(final String sql, final Object... params) { List<T> list = getHibernateTemplate().executeFind( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { SQLQuery sqlQuery = session.createSQLQuery(sql).addEntity(Trade.class); if (params != null && params.length != 0) { for (int i = 0; i < params.length; i++) { System.out.println(params[i]); sqlQuery.setParameter(i, params[i]); } } return sqlQuery.list(); } }); System.out.println(list.size()); return list; } } package com.clear.dao; import java.io.Serializable; import java.util.List; public class BaseDaoSupport<K extends Serializable, T> implements IBaseDaoSupport<K, T> { private IBaseDaoSupport<K, T> baseDaoSupport; public IBaseDaoSupport<K, T> getBaseDaoSupport() { return baseDaoSupport; } public void setBaseDaoSupport(IBaseDaoSupport<K, T> baseDaoSupport) { this.baseDaoSupport = baseDaoSupport; } public List<T> findEntityAll() { return baseDaoSupport.findEntityAll(); } public T findEntityById(K id) { return baseDaoSupport.findEntityById(id); } public List<T> findEntityByQueryLanguage(String ql, Object... params) { return baseDaoSupport.findEntityByQueryLanguage(ql, params); } public Boolean isDeleteEntity(K id) { return baseDaoSupport.isDeleteEntity(id); } public Boolean isSaveEntity(T entity) { return baseDaoSupport.isSaveEntity(entity); } public Boolean isUpdateEntity(T entity) { return baseDaoSupport.isUpdateEntity(entity); } public List<T> findEntityBySQLQuery(String sql, Object... params) { return baseDaoSupport.findEntityBySQLQuery(sql, params); } } 我在spring里面注入的是BaseDaoSupportBySpring类,在BaseDaoSupportBySpring类中使用entityClass却拿不到泛型的类信息,如果直接让其余的dao实现类继承BaseDaoSupportBySpring是可以拿到的,问题是现在我使用的是依赖注入.....求解决方案
SpringBoot集成shiro-redis遇到的问题(已解决)
在通过***(SysUser) SecurityUtils.getSubject().getPrincipal()*** 获取当前登录对象时,**SecurityUtils.getSubject().getPrincipal()**是正确的对象。 当强转时报错com.spring.model.system.SysUser cannot be cast to com.spring.model.system.SysUser。 求解本人猜测是redis对象序列化反序列化导致,因为shiro没有集成redis时是正确的,但是经过测试,不走shiro单独存储读取对象是没有问题的,这块不是太懂,求大神解答 下面是相关的配置代码 redis配置 ``` @Configuration @EnableCaching @EnableRedisHttpSession public class RedisConfig extends CachingConfigurerSupport { @Bean public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) { RedisCacheManager manager = new RedisCacheManager(redisTemplate); manager.setDefaultExpiration(3600);//设置默认过期时间 return manager; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } } ``` ``` shiro配置 @Configuration public class ShiroConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.timeout}") private int timeout; @Value("${spring.redis.password}") private String password; @Bean public ShiroDialect shiroDialect() { return new ShiroDialect(); } @Bean public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); //拦截器. Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); // 配置不会被拦截的链接 顺序判断 filterChainDefinitionMap.put("/doLogin", "anon"); filterChainDefinitionMap.put("/css/**", "anon"); filterChainDefinitionMap.put("/images/**", "anon"); filterChainDefinitionMap.put("/js/**", "anon"); filterChainDefinitionMap.put("/libs/**", "anon"); // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面 shiroFilterFactoryBean.setLoginUrl("/login"); //未授权界面; shiroFilterFactoryBean.setUnauthorizedUrl("/403"); // 配置需要验证登录后访问的链接 filterChainDefinitionMap.put("/**", "authc"); // 从数据库获取 // List<AdminMenu> list = systemService.selectAllMenu(); // // for (AdminMenu menu : list) { // filterChainDefinitionMap.put(menu.getMenuUrl(), "authc"); // } shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } /** * 凭证匹配器 * (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了) * * @return */ @Bean public HashedCredentialsMatcher hashedCredentialsMatcher() { HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法; hashedCredentialsMatcher.setHashIterations(1);//散列的次数 return hashedCredentialsMatcher; } @Bean public SecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(myShiroRealm()); // 自定义缓存实现 使用redis securityManager.setCacheManager(cacheManager()); // 自定义session管理 使用redis securityManager.setSessionManager(sessionManager()); //注入记住我管理器; securityManager.setRememberMeManager(rememberMeManager()); return securityManager; } /** * 身份认证realm; (自定义,账号密码校验;权限等) * * @return */ @Bean public MyShiroRealm myShiroRealm() { MyShiroRealm myShiroRealm = new MyShiroRealm(); myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return myShiroRealm; } /** * 配置shiro redisManager * <p> * 使用的是shiro-redis开源插件 * * @return */ public RedisManager redisManager() { RedisManager redisManager = new RedisManager(); redisManager.setHost(host); redisManager.setPort(port); redisManager.setExpire(1800);// 配置缓存过期时间 redisManager.setTimeout(timeout); redisManager.setPassword(password); return redisManager; } /** * cacheManager 缓存 redis实现 * <p> * 使用的是shiro-redis开源插件 * * @return */ @Bean public RedisCacheManager cacheManager() { RedisCacheManager redisCacheManager = new RedisCacheManager(); redisCacheManager.setRedisManager(redisManager()); return redisCacheManager; } /** * RedisSessionDAO shiro sessionDao层的实现 通过redis * <p> * 使用的是shiro-redis开源插件 */ @Bean public RedisSessionDAO redisSessionDAO() { RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); redisSessionDAO.setRedisManager(redisManager()); return redisSessionDAO; } /** * Session Manager * <p> * 使用的是shiro-redis开源插件 */ @Bean public DefaultWebSessionManager sessionManager() { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setSessionDAO(redisSessionDAO()); return sessionManager; } /** * cookie对象; * * @return */ public SimpleCookie rememberMeCookie() { //这个参数是cookie的名称,对应前端的checkbox的name = rememberMe SimpleCookie simpleCookie = new SimpleCookie("rememberMe"); //<!-- 记住我cookie生效时间7天 ,单位秒;--> simpleCookie.setMaxAge(604800); return simpleCookie; } /** * cookie管理对象;记住我功能 * * @return */ @Bean public CookieRememberMeManager rememberMeManager() { CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); cookieRememberMeManager.setCookie(rememberMeCookie()); //rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位) cookieRememberMeManager.setCipherKey(Base64.decode("3AvVhmFLUs0KTA3Kprsdag==")); return cookieRememberMeManager; } /** * 开启shiro aop注解支持. * 使用代理方式;所以需要开启代码支持; * * @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } } ``` # 去除spring-boot-devtools热部署jar包即可,具体原因不详
spring2.5.6 配置 openJpa 异常
最近在做一个小列子,原本是用配置文件方式注入的,之后我想改为用注解的方式注入,问题就出现了。 错误代码如下: [code="java"]2010-2-4 22:18:04 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet default threw exception java.lang.IllegalArgumentException: entityManagerFactory or jpaTemplate is required at org.springframework.orm.jpa.support.JpaDaoSupport.checkDaoConfig(JpaDaoSupport.java:119) at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:671) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:610) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:499) at org.springframework.beans.factory.annotation.InjectionMetadata.injectMethods(InjectionMetadata.java:117) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:253) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:998) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:671) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:610) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1076) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:982) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:329) at com.opensymphony.xwork2.spring.SpringObjectFactory.autoWireBean(SpringObjectFactory.java:168) at com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:155) at com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:129) at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:143) at com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:113) at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:275) at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:365) at com.opensymphony.xwork2.DefaultActionInvocation.access$000(DefaultActionInvocation.java:38) at com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:83) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.<init>(DefaultActionInvocation.java:74) at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:189) at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:41)[code="java"][/code] at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:494) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619)[/code] java代码如下: [code="java"] @Repository public class ExamDAOImpl extends JpaDaoSupport implements ExamDAO{ private String hql = "from Exam a "; //新增试卷 public void create(Exam exam) { this.getJpaTemplate().persist(exam); } //修改试卷 public void update(Exam exam) { this.getJpaTemplate().merge(exam); } //删除试卷 public void delete(Exam exam) { this.getJpaTemplate().remove(this.getJpaTemplate().merge(exam)); } //根据id获取试卷信息 public Exam query(int id) { Exam exam = this.getJpaTemplate().find(Exam.class, id); return exam; } //获取所有试卷的信息 @SuppressWarnings("unchecked") public List<Exam> queryList() { List<Exam> list = new ArrayList<Exam>(); list = this.getJpaTemplate().find(hql); return list; } } @Namespace("/") @Results({@Result("jsp/examManagement.jsp"), @Result(name="createQuestion", value = "jsp/questionManagement.jsp"), @Result(name="exam", value = "jsp/exam.jsp"), @Result(name="examResult", value = "jsp/examResult.jsp")}) public class ExamAction extends ActionSupport { private static final long serialVersionUID = 5192939935859483841L; //新增试卷信息 public String create() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); //进行新增 getExamService().create(exam); //获取已有的试卷信息 List<Exam> listExams = getExamService().queryList(); //将已有的试卷信息传递给页面 req.setAttribute("listExams", listExams); //存放消息 req.setAttribute("msg", "新增成功"); return SUCCESS; } //修改试卷信息 public String update() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); //进行修改 getExamService().update(exam); //获取已有的试卷信息 List<Exam> listExams = getExamService().queryList(); //将已有的试卷信息传递给页面 req.setAttribute("listExams", listExams); //存放消息 req.setAttribute("msg", "修改成功"); return SUCCESS; } //删除试卷信息 public String delete() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); //进行删除 getExamService().delete(exam); //获取已有的试卷信息 List<Exam> listExams = getExamService().queryList(); //将已有的试卷信息传递给页面 req.setAttribute("listExams", listExams); //存放消息 req.setAttribute("msg", "删除成功"); return SUCCESS; } //设定该试卷下的题目 public String createQuestion() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); exam = getExamService().query(exam.getId()); //获取该试卷题目下已有的题目 Set<Question> listQuestions = exam.getQuestion(); //将该试卷题目下已有的题目信息传递给页面 req.setAttribute("listQuestions", listQuestions); //将该试卷信息传递给页面 req.setAttribute("exam", exam); //存放消息 req.setAttribute("msg", "欢迎进入" + exam.getName() + "试题题目管理系统"); return "createQuestion"; } //进行考试 public String exam() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); exam = getExamService().query(exam.getId()); //将该试卷信息传递给页面 req.setAttribute("exam", exam); //存放消息 req.setAttribute("msg", "欢迎您开始《" + exam.getName() + "》试卷"); return "exam"; } //统计试卷成绩 public String submitExam() { HttpServletRequest req = ServletActionContext.getRequest(); //获取试卷信息 Exam exam = new Exam(); exam = getExamService().query(Integer.valueOf(req.getParameter("examId"))); //定义该此考试的分数 float result = 0f; //获取该试卷下的题目 Set<Question> listQuestions = exam.getQuestion(); Iterator<Question> iterator = listQuestions.iterator(); //获取每个题目下的项目 while (iterator != null && iterator.hasNext()) { Question question = (Question)iterator.next(); //获取该题目下的项目 List<QuestionItem> listQuestionItems = question.getQuestionItem(); //获取用户选择的题目下的项目 Assert.notNull((String)req.getParameter(question.getId() + "")); int questionId = Integer.valueOf((String)req.getParameter(question.getId() + "")); //累计用户提交的题目下的项目 for (int j = 0; listQuestionItems != null && j < listQuestionItems.size(); j++) { QuestionItem questionItem = (QuestionItem)listQuestionItems.get(j); if(questionId == questionItem.getId()) { if (questionItem.getIsOk() == 1) { //统计成绩 result = result + question.getPoint(); break; } } } } //将该试卷信息传递给页面 req.setAttribute("exam", exam); //将成绩传递给页面 req.setAttribute("result", result); //存放消息 req.setAttribute("msg", "欢迎您查看《" + exam.getName() + "》试卷的成绩"); return "examResult"; } public String index() { HttpServletRequest req = ServletActionContext.getRequest(); //获取已有的试卷信息 List<Exam> listExams = getExamService().queryList(); //将已有的试卷信息传递给页面 //System.out.println("listExams.size==="+listExams.size()); req.setAttribute("listExams", listExams); req.setAttribute("msg", "欢迎进入试卷题目管理系统"); return SUCCESS; } //获取试卷业务逻辑 public ExamService getExamService(){ return examService; } //设定试卷业务逻辑 @Autowired public void setExamService(ExamService examService){ this.examService = examService; } private ExamService examService; //获取试题项目业务逻辑 public QuestionItemService getQuestionItemService(){ return questionItemService; } //设定试题项目业务逻辑 @Autowired public void setQuestionItemService(QuestionItemService questionItemService){ this.questionItemService = questionItemService; } private QuestionItemService questionItemService; //封装试卷基本信息 public Exam getExamBean(HttpServletRequest req, HttpServletResponse res) { Exam exam = new Exam(); try { //判断是否是新增或者修改还是删除,如果是新增则不需要id String hh = req.getParameter("examId" + (String)req.getParameter("checkbox") + ""); if (!"".equals(hh) && hh != null) { exam.setId(Integer.valueOf(req.getParameter("examId" + (String)req.getParameter("checkbox") + ""))); } //获取基本信息 exam.setName(((String)req.getParameter("name" + (String)req.getParameter("checkbox") + ""))); } catch (Exception ex) { ex.printStackTrace(); } return exam; } } [/code] struts和spring的配置文件如下: [code="java"] <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!--表示可以使用动态方法调用,即userAction!delete.action的形式--> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <!--表示struts处于开发状态--> <constant name="struts.devMode" value="true" /> <constant name="struts.convention.classes.reload" value="true" /> <constant name="struts.objectFactory.spring.autoWire" value="type" /> <!--使用默认的命名空间、即根目录/,在访问的时候,直接http://localhost:8080/webExam/userAction!delete.action--> <!--<package name="default" extends="struts-default"> 定义动态方法调用examAction!*.action <action name="examAction" class="examAction"> <result>jsp/examManagement.jsp</result> <result name="createQuestion">jsp/questionManagement.jsp</result> <result name="exam">jsp/exam.jsp</result> <result name="examResult">jsp/examResult.jsp</result> </action> 定义动态方法调用questionAction!*.action <action name="questionAction" class="questionAction"> <result>jsp/questionManagement.jsp</result> <result name="createItem">jsp/questionItemManagement.jsp</result> </action> 定义动态方法调用questionItemAction!*.action <action name="questionItemAction" class="questionItemAction"> <result>jsp/questionItemManagement.jsp</result> </action> </package>--> </struts> <?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:http-conf="http://cxf.apache.org/transports/http/configuration" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" default-lazy-init="true"> <context:component-scan base-package="com.webExam.dao.impl,com.webExam.service.impl"/> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="entityManager"/> <property name="jpaProperties"> <props></props> </property> </bean> </beans> [/code] persistence文件如下: [code="java"]<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <!--定义持久单元--> <persistence-unit name="entityManager" transaction-type="RESOURCE_LOCAL"> <!--这里采用Hibernate提供的持久化类--> <provider>org.hibernate.ejb.HibernatePersistence</provider> <!--定义持久化属性--> <properties> <!--定义方言、fetch深度、是否显示sql--> <property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect" /> <property name="hibernate.max_fetch_depth" value="3" /> <property name="hibernate.show_sql" value="true" /> <!--定义是否自动生成表,create表示每次加载都重新生成,update表示每次加载只是更新表--> <property name="hibernate.hbm2ddl.auto" value="update" /> <!--定义数据库连接的相关属性--> <property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver" /> <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:FLOW" /> <!--定义数据库连接的用户名、密码等--> <property name="hibernate.connection.username" value="arch" /> <property name="hibernate.connection.password" value="arch" /> </properties> </persistence-unit> </persistence>[/code]
spring 注解 空指针错误
先贴异常吧: [code="java"]cn.buct.inteWeb.user.web.LoginAction.login(LoginAction.java:52) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) java.lang.reflect.Method.invoke(Unknown Source) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) java.lang.Thread.run(Unknown Source)[/code] 下面是代码 [code="java"] package cn.buct.inteWeb.user.web; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import cn.buct.inteWeb.common.web.AbstractAjaxAction; import cn.buct.inteWeb.user.entity.User; import cn.buct.inteWeb.user.service.UserManager; import cn.buct.inteWeb.Constants; import cn.buct.inteWeb.SessionHolder; public class LoginAction extends AbstractAjaxAction <User,Long>{ private static final long serialVersionUID = 1L; private UserManager userManager; private static final String USER_LOGIN = "index"; private String userName; private String password; private String message; public String login() { String userName2 = getRequest().getParameter("userName"); System.out.println("userName=" + userName2); String password2 = getRequest().getParameter("password"); System.out.println("password=" + password2); System.out.println(userManager); /** * 判断当前是否已经登录 */ if(SessionHolder.isLogined(getRequest())) { return USER_LOGIN; } /** * 登录验证码显示控制begin */ long count = 1; if (null != getRequest().getSession() && null != getRequest().getSession().getAttribute("count")) { count = ((Long) getRequest().getSession().getAttribute("count")) + 1; } getRequest().getSession().setAttribute("count", count); if (StringUtils.isBlank(userName) && StringUtils.isNotBlank(getRequest().getParameter("userName"))) { userName = getRequest().getParameter("userName").trim(); } // 判断用户是否存在 User user = userManager.getByName(userName); if (user == null) { message = Constants.LOGIN_USER_ERROR_MSG; return USER_LOGIN; } return null; } public String loginInput() { return USER_LOGIN; } @Override protected BaseEntityManager<User, Long> getManager() { // TODO Auto-generated method stub return null; } @Override protected Long getId() { // TODO Auto-generated method stub return null; } public void setUserManager(UserManager userManager) { this.userManager = userManager; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } [/code] web.xml文件: [code="xml"] <?xml version="1.0" encoding="UTF-8"?> <web-app id="contact" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>test</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:spring/applicationContext.xml classpath*:spring/modules/applicationContext*.xml classpath*:spring/modules/applicationContext-dnsis-soa.xml <!-- classpath*:spring/modules/applicationContext-quartz-client.xml --> </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!-- encodingFilter--> <filter> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- struts2Filter--> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> <init-param> <param-name>actionPackages</param-name> <param-value>cn.buct</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <session-config> <session-timeout>20</session-timeout> </session-config> </web-app> [/code] struts.xml [code="xml"] <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="messageResource" /> <constant name="struts.multipart.maxSize" value="1000000000" /> <!-- <constant name="struts-devMode" Value="true"> --> <constant name="struts.devMode" value="true"/> <package name="user" extends="struts-default" namespace="/user"> <action name="Login" class="cn.buct.inteWeb.user.web.LoginAction"> <result name="index">/view/user-login.jsp</result> </action> </package> </struts> [/code] applicationContext.xml [code="xml"] <?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:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" default-lazy-init="true" default-autowire="byName"> <description></description> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" lazy-init="false"> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_NEVER" /> <property name="ignoreResourceNotFound" value="true" /> <property name="order" value="1" /> <property name="ignoreUnresolvablePlaceholders" value="true" /> <property name="locations"> <list> <value>classpath:application.properties</value> </list> </property> </bean> <!-- 使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入 --> <context:component-scan base-package="cn.knet" /> <!-- 使用aop定义事务 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <aop:config proxy-target-class="true"> <aop:advisor pointcut="execution(* cn.knet.dnsis.*.service.*.*(..))" advice-ref="txAdvice" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="select*" read-only="true" /> <tx:method name="*" /> </tx:attributes> </tx:advice> <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" /> <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}" /> <property name="maxActive" value="30" /> </bean> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="classpath:ibatis/SqlMapConfig.xml" /> </bean> <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate" /> <!-- freemarker template engine --> <bean id="templateEngine" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="freemarkerSettings"> <props> <prop key="template_update_delay">0</prop> <prop key="default_encoding">UTF-8</prop> <prop key="locale">zh_CN</prop> </props> </property> </bean> </beans> [/code] 麻烦多指教了。
Spring 事件类Demo,出错了,提示未添加Bean,但我找不到啊
/** * 自定义事件 */ public class DemoEvent extends ApplicationEvent{ private static final long serialVerSionUID = 1L; private String msg; public DemoEvent(Object source,String msg) { super(source); this.msg = msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } /** * 事件监听器 */ @Component //实现ApplicationListener接口,并指定监听的事件类型 public class DemoListener implements ApplicationListener<DemoEvent>{ //使用onApplicationEvent方法对消息进行接受处理 public void onApplicationEvent(DemoEvent event) { String msg = event.getMsg(); System.out.println("我(bean-demoListener)接受到了bean-demoPublisger发布的消息:" + msg); } } /** * 事件发布类 */ @Component public class DemoPublisher { @Autowired ApplicationContext applicationContext; //注入ApplicationContext用来发布事件 public void publish(String msg) { //使用ApplicationContext的publishEvent方法来发布 applicationContext.publishEvent(new DemoEvent(this,msg)); } } /** * 配置类 */ @Configuration @Component("com.jiudao.event") public class EventConfig { } /** * 运行 */ public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class); DemoPublisher demoPublisher = context.getBean(DemoPublisher.class); demoPublisher.publish("hello application event"); context.close(); } } 运行提示:Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.jiudao.event.DemoPublisher] is defined at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:371) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:972) at com.jiudao.event.Main.main(Main.java:14)
Spring 3.0+ Hibernate 3.3 泛型 注解管理Bean 出现问题 郁闷!
参照网上的Demo 自己也弄了个泛型注解 BaseDao 里面 的gedao 是null 高手们给看一下 [code="java"]package com.zw.core; import java.io.Serializable; import java.util.List; public interface IBaseDao<T, PK extends Serializable> { public T getById(PK id); public List<T> getAll(); public T load(PK id); public void load(T entityObject, PK id); public void delete(T entityObject); public void deleteById(PK id); public void refresh(T entityObject); public void evict(T entityObject); public void save(T entityObject); public void clear(); }[/code] [code="java"]package com.zw.core; import java.io.Serializable; import java.util.List; public class BaseDao<T, PK extends Serializable> implements IBaseDao<T, PK> { protected Class<T> entityClass;// DAO所管理的Entity类型. private GenericEntityDao<T, PK> gedao; public Class<T> getEntityClass() { return entityClass; } public void setEntityClass(Class<T> entityClass) { this.entityClass = entityClass; } public GenericEntityDao<T, PK> getGedao() { return gedao; } public void setGedao(GenericEntityDao<T, PK> gedao) { this.gedao = gedao; } /** * 让spring提供构造函数注入 */ public BaseDao(Class<T> type) { this.entityClass = type; } public BaseDao() { } public void delete(T entityObject) { gedao.delete(entityObject); } public void deleteById(PK id) { gedao.deleteById(id); } public void evict(T entityObject) { gedao.evict(entityObject); } public List<T> getAll() { return gedao.getAll(); } public T getById(PK id) { return gedao.getById(id); } public T load(PK id) { return gedao.load(id); } public void load(T entityObject, PK id) { gedao.load(entityObject, id); } public T merge(T entityObject) { return gedao.merge(entityObject); } public void refresh(T entityObject) { gedao.refresh(entityObject); } public void save(T entityObject) { System.out.println("gedao:"+gedao); gedao.save(entityObject); } public void clear() { } } [/code] [code="java"]package com.zw.core; import java.io.Serializable; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class GenericEntityDao<T, PK extends Serializable> extends HibernateDaoSupport { protected Class<T> entityClass;// DAO所管理的Entity类型. public GenericEntityDao() { } public GenericEntityDao(Class<T> entityClass) { this.entityClass = entityClass; } @SuppressWarnings("unchecked") public T getById(PK id) { return (T) this.getHibernateTemplate().get(this.entityClass, id); } @SuppressWarnings("unchecked") public List<T> getAll() { return (List<T>) (this.getHibernateTemplate().loadAll(this.entityClass)); } @SuppressWarnings("unchecked") public T load(PK id) { return (T) this.getHibernateTemplate().load(this.entityClass, id); } public void load(T entityObject, PK id) { this.getHibernateTemplate().load(entityObject, id); } public void delete(T entityObject) { this.getHibernateTemplate().delete(entityObject); } public void deleteById(PK id) { this.delete(this.getById(id)); } public void refresh(T entityObject) { this.getHibernateTemplate().refresh(entityObject); } public void evict(T entityObject) { this.getHibernateTemplate().evict(entityObject); } public void save(T entityObject) { this.getHibernateTemplate().saveOrUpdate(entityObject); } @SuppressWarnings("unchecked") public T merge(T entityObject) { return (T) this.getHibernateTemplate().merge(entityObject); } } [/code] ToplMSoftDAO [code="java"]package com.zw.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Repository; import com.zw.core.BaseDao; import com.zw.domain.ToplMSoft; @Repository("toplMSoftDAO") public class ToplMSoftDAO extends BaseDao<ToplMSoft,Integer> { private static final Log log = LogFactory.getLog(ToplMSoftDAO.class); } [/code] [code="java"] <?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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 使用外部文件配置数据源的属性 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <!-- 外部文件地址 --> <value>classpath:database_conn.properties </value> </list> </property> <property name="fileEncoding" value="utf-8" /> </bean> <!-- 配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${driverClassName}" /> <property name="jdbcUrl" value="${url}" /> <property name="user" value="${username}" /> <property name="password" value="${password}" /> <property name="minPoolSize" value="5" /> <property name="maxPoolSize" value="20" /> <property name="initialPoolSize" value="10" /> <property name="maxIdleTime" value="60" /> <property name="acquireIncrement" value="5" /> <property name="maxStatements" value="0" /> <property name="idleConnectionTestPeriod" value="60" /> <property name="acquireRetryAttempts" value="30" /> <property name="breakAfterAcquireFailure" value="true" /> <property name="testConnectionOnCheckout" value="false" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <!-- 引用数据源 --> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="namingStrategy"> <bean class="org.hibernate.cfg.ImprovedNamingStrategy" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size} </prop> <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size} </prop> </props> </property> <property name="packagesToScan" value="com.zw.domain" /> <!--</property> <property name="annotatedClasses"> <list> <value>org.wpms.kernel.user.po.User</value> </list> </property>--> </bean> <!-- 定义了与实体相关的dao --> <bean id="genericEntityDao" class="com.zw.core.GenericEntityDao" scope="prototype" lazy-init="true"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <!--使用泛型DAO作为抽象基类 abstract="true" --> <bean id="baseDao" class="com.zw.core.BaseDao" abstract="true" depends-on="genericEntityDao"> <property name="gedao"> <ref bean="genericEntityDao" /> </property> </bean> <!-- 使Spring关注Annotation --> <context:annotation-config /> <!-- 让Spring通过自动扫描来查询和管理Bean --> <context:component-scan base-package="com.zw" /> <!-- <bean id="toplMSoftDAO" class="com.zw.dao.ToplMSoftDAO" parent="baseDao"></bean> <bean id="toplMSoftServiceImpl" class="com.zw.service.impl.ToplMSoftServiceImpl"> <property name="toplMSoftDAO" ref="toplMSoftDAO" /> </bean> --> <!-- 业务类bean的实现类标注了@Transactional注解,所以会被 tx:annotation-driven注解驱动自动织入事务增强 --> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <!--注解式事务配置驱动--> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> </beans> [/code] ToplMSoft [code="java"] package com.zw.domain; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "topl_m_soft", catalog = "zwtest") public class ToplMSoft implements java.io.Serializable { // Fields /** * */ private static final long serialVersionUID = -5245203859352468180L; private Integer softkey; private String softname; private String softtypekey; private String softversion; private String softsize; private String providername; private String providersite; private String downsite1; private String softfaceurl; private String issuestate; private String fruntime; private String sruntime; private Float marketprice; private Float storeprice; private String ifourcommend; private String ifspprice; private String softenglishname; private String runLink; private String runnum; private String downnum; private String column1; private String column2; private String column3; private String contact; private Timestamp createdate; private Timestamp updatedate; // Constructors /** default constructor */ public ToplMSoft() { } // Property accessors @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "softkey", unique = true, nullable = false) public Integer getSoftkey() { return this.softkey; } public void setSoftkey(Integer softkey) { this.softkey = softkey; } @Column(name = "softname", nullable = false, length = 100) public String getSoftname() { return this.softname; } public void setSoftname(String softname) { this.softname = softname; } @Column(name = "softtypekey", nullable = false, length = 10) public String getSofttypekey() { return this.softtypekey; } public void setSofttypekey(String softtypekey) { this.softtypekey = softtypekey; } @Column(name = "softversion", length = 20) public String getSoftversion() { return this.softversion; } public void setSoftversion(String softversion) { this.softversion = softversion; } @Column(name = "softsize", length = 20) public String getSoftsize() { return this.softsize; } public void setSoftsize(String softsize) { this.softsize = softsize; } @Column(name = "providername", length = 200) public String getProvidername() { return this.providername; } public void setProvidername(String providername) { this.providername = providername; } @Column(name = "providersite", length = 100) public String getProvidersite() { return this.providersite; } public void setProvidersite(String providersite) { this.providersite = providersite; } @Column(name = "downsite1", length = 300) public String getDownsite1() { return this.downsite1; } public void setDownsite1(String downsite1) { this.downsite1 = downsite1; } @Column(name = "softfaceurl", length = 200) public String getSoftfaceurl() { return this.softfaceurl; } public void setSoftfaceurl(String softfaceurl) { this.softfaceurl = softfaceurl; } @Column(name = "issuestate", length = 10) public String getIssuestate() { return this.issuestate; } public void setIssuestate(String issuestate) { this.issuestate = issuestate; } @Column(name = "fruntime", length = 10) public String getFruntime() { return this.fruntime; } public void setFruntime(String fruntime) { this.fruntime = fruntime; } @Column(name = "sruntime", length = 10) public String getSruntime() { return this.sruntime; } public void setSruntime(String sruntime) { this.sruntime = sruntime; } @Column(name = "marketprice", precision = 10, scale = 0) public Float getMarketprice() { return this.marketprice; } public void setMarketprice(Float marketprice) { this.marketprice = marketprice; } @Column(name = "storeprice", precision = 10, scale = 0) public Float getStoreprice() { return this.storeprice; } public void setStoreprice(Float storeprice) { this.storeprice = storeprice; } @Column(name = "ifourcommend", length = 2) public String getIfourcommend() { return this.ifourcommend; } public void setIfourcommend(String ifourcommend) { this.ifourcommend = ifourcommend; } @Column(name = "ifspprice", length = 2) public String getIfspprice() { return this.ifspprice; } public void setIfspprice(String ifspprice) { this.ifspprice = ifspprice; } @Column(name = "softenglishname", length = 200) public String getSoftenglishname() { return this.softenglishname; } public void setSoftenglishname(String softenglishname) { this.softenglishname = softenglishname; } @Column(name = "runLink", length = 300) public String getRunLink() { return this.runLink; } public void setRunLink(String runLink) { this.runLink = runLink; } @Column(name = "runnum", length = 10) public String getRunnum() { return this.runnum; } public void setRunnum(String runnum) { this.runnum = runnum; } @Column(name = "downnum", length = 10) public String getDownnum() { return this.downnum; } public void setDownnum(String downnum) { this.downnum = downnum; } @Column(name = "column1", nullable = false, length = 2000) public String getColumn1() { return this.column1; } public void setColumn1(String column1) { this.column1 = column1; } @Column(name = "column2", length = 200) public String getColumn2() { return this.column2; } public void setColumn2(String column2) { this.column2 = column2; } @Column(name = "column3", length = 200) public String getColumn3() { return this.column3; } public void setColumn3(String column3) { this.column3 = column3; } @Column(name = "contact", length = 2) public String getContact() { return this.contact; } public void setContact(String contact) { this.contact = contact; } @Column(name = "createdate", length = 19) public Timestamp getCreatedate() { return this.createdate; } public void setCreatedate(Timestamp createdate) { this.createdate = createdate; } @Column(name = "updatedate", length = 19) public Timestamp getUpdatedate() { return this.updatedate; } public void setUpdatedate(Timestamp updatedate) { this.updatedate = updatedate; } } [/code] service 层 ToplMSoftService [code="java"] package com.zw.service; import com.zw.domain.ToplMSoft; public interface ToplMSoftService { public void save(ToplMSoft tps); } [/code] ToplMSoftServiceImpl [code="java"]package com.zw.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.zw.core.BaseDao; import com.zw.core.IBaseDao; import com.zw.domain.ToplMSoft; import com.zw.service.ToplMSoftService; @Transactional(readOnly = true) //对业务类进行事务增强的标注 @Service //声明此类为业务逻辑层的类 public class ToplMSoftServiceImpl implements ToplMSoftService { @Resource(name ="toplMSoftDAO") private IBaseDao <ToplMSoft, Integer> toplMSoftDAO; public IBaseDao<ToplMSoft, Integer> getToplMSoftDAO() { return toplMSoftDAO; } public void setToplMSoftDAO(IBaseDao<ToplMSoft, Integer> toplMSoftDAO) { this.toplMSoftDAO = toplMSoftDAO; } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void save(ToplMSoft tps) { System.out.println("toplMSoftDAO:"+toplMSoftDAO); this.toplMSoftDAO.save(tps); } } [/code] Test: [code="java"] package com.zw.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.zw.domain.ToplMSoft; import com.zw.service.ToplMSoftService; import com.zw.service.impl.ToplMSoftServiceImpl; public class TestHibernate { public static void main(String[] args) { ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); ToplMSoftService dao= (ToplMSoftServiceImpl) ctx.getBean("toplMSoftServiceImpl"); //GenericEntityDao dao= (GenericEntityDao) ctx.getBean("ToplMSoftDAO"); System.out.println("1111111111:"+dao); ToplMSoft tps=new ToplMSoft(); tps.setSoftname("测试11111111"); tps.setSofttypekey("2"); tps.setColumn1("xsdasdasdasd"); dao.save(tps); } } [/code] 控制台输出 我在BaseDao save方法里面打出 System.out.println("gedao:"+gedao); 为null [code="java"] 1111111111:com.zw.service.impl.ToplMSoftServiceImpl@6e3e5e toplMSoftDAO:com.zw.dao.ToplMSoftDAO@10718b7 gedao:null Exception in thread "main" java.lang.NullPointerException at com.zw.core.BaseDao.save(BaseDao.java:60) at com.zw.service.impl.ToplMSoftServiceImpl.save(ToplMSoftServiceImpl.java:31) at com.zw.service.impl.ToplMSoftServiceImpl$$FastClassByCGLIB$$7aa0faa6.invoke(<generated>) at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191) at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:692) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:107) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:625) at com.zw.service.impl.ToplMSoftServiceImpl$$EnhancerByCGLIB$$ded4983e.save(<generated>) at com.zw.test.TestHibernate.main(TestHibernate.java:22) [/code] 如果不用注解 直接在applicationContext.xml配置 [code="java"] <bean id="toplMSoftDAO" class="com.zw.dao.ToplMSoftDAO" parent="baseDao"></bean> <bean id="toplMSoftServiceImpl" class="com.zw.service.impl.ToplMSoftServiceImpl"> <property name="toplMSoftDAO" ref="toplMSoftDAO" /> </bean> [/code] 就不会报错 可以直接插入数据. 对Spring了解的不深 比较困惑 朋友们帮忙解答一下 谢谢
关于struts2+spring2+hibernate3的问题
信息: Using DataSource [com.mchange.v2.c3p0.ComboPooledDataSource@e64686[ acquir eIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, allUsers -> [root], autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAc quireFailure -> false, checkoutTimeout -> 0, connectionTesterClassName -> com.mc hange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 15ad5c6, descripti on -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> e64686, idleConnect ionTestPeriod -> 900, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:33 06/mysql?useUnicode=true&characterEncoding=UTF-8, maxIdleTime -> 600, maxPoolSiz e -> 50, maxStatements -> 100, maxStatementsPerConnection -> 0, minPoolSize -> 2 , numHelperThreads -> 10, preferredTestQuery -> null, properties -> {user=****** , password=******}, propertyCycle -> 300, testConnectionOnCheckin -> false, test ConnectionOnCheckout -> false, usesTraditionalReflectiveProxies -> false ]] of H ibernate SessionFactory for HibernateTransactionManager 2010-11-15 9:29:05 org.springframework.web.context.ContextLoader initWebApplicat ionContext 信息: Root WebApplicationContext: initialization completed in 4119 ms 2010-11-15 9:29:06 org.apache.catalina.core.StandardContext start [color=red]严重: Error listenerStart 2010-11-15 9:29:06 org.apache.catalina.core.StandardContext start 严重: Context [/ssh] startup failed due to previous errors 2010-11-15 9:29:06 org.springframework.context.support.AbstractApplicationContex t doClose[/color] 信息: Closing org.springframework.web.context.support.XmlWebApplicationContext@7 6e369: display name [Root WebApplicationContext]; startup date [Mon Nov 15 09:29 :01 CST 2010]; root of context hierarchy 2010-11-15 9:29:06 org.springframework.beans.factory.support.DefaultSingletonBea nRegistry destroySingletons 信息: Destroying singletons in org.springframework.beans.factory.support.Default ListableBeanFactory@4c4975: defining beans [propertyConfigurer,dataSource,sessio nFactory,transactionManager,transactionInterceptor,org.springframework.aop.frame work.autoproxy.BeanNameAutoProxyCreator,LoginAction,genericDao,userDao,userServi ce]; root of factory hierarchy 2010-11-15 9:29:06 org.springframework.orm.hibernate3.AbstractSessionFactoryBean destroy 信息: Closing Hibernate SessionFactory 2010-11-15 9:29:07 org.springframework.web.servlet.FrameworkServlet initServletB ean 信息: FrameworkServlet 'dispatcher': initialization started 2010-11-15 9:29:07 org.springframework.context.support.AbstractApplicationContex t prepareRefresh 信息: Refreshing org.springframework.web.context.support.XmlWebApplicationContex 没集成hibernate3时,struts2+spring2还是好的,不知道是不是包冲突了,但我加的包的版本都是合适的呀 struts2:struts-2.0.14 spring2:spring-framework-2.0.8 hibernate3:hibernate-distribution-3.6.0.Final 希望大大们讲解一下,问题是哪里? applicationContext-hibernate.xml如下: [code="xml"]<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> <beans> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <!-- <value>WEB-INF/mail.properties</value>--> <value>WEB-INF/jdbc.properties</value> <!-- <value>WEB-INF/oscache.properties</value>--> </list> </property> </bean> <!-- MailSender used by EmailAdvice --> <!-- <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="${mail.host}"/> </bean> --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" dependency-check="none"> <property name="driverClass"> <value>${datasource.driverClassName}</value> </property> <property name="jdbcUrl"> <value>${datasource.url}</value> </property> <property name="user"> <value>${datasource.username}</value> </property> <property name="password"> <value>${datasource.password}</value> </property> <property name="acquireIncrement"> <value>${c3p0.acquireIncrement}</value> </property> <property name="initialPoolSize"> <value>${c3p0.initialPoolSize}</value> </property> <property name="minPoolSize"> <value>${c3p0.minPoolSize}</value> </property> <property name="maxPoolSize"> <value>${c3p0.maxPoolSize}</value> </property> <property name="maxIdleTime"> <value>${c3p0.maxIdleTime}</value> </property> <property name="idleConnectionTestPeriod"> <value>${c3p0.idleConnectionTestPeriod}</value> </property> <property name="maxStatements"> <value>${c3p0.maxStatements}</value> </property> <property name="numHelperThreads"> <value>${c3p0.numHelperThreads}</value> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource" /> </property> <property name="mappingResources"> <list> <value>cn/com/aaCompany/app/biz/hibernate/User.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop> <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop> </props> </property> </bean> <!-- 配置事务管理器bean,使用 HibernateTransactionManager事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <!-- 为事务管理器注入sessionFactory" --> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 配置事务拦截器Bean --> <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <!-- 为事务拦截器bean注入一个事物管理器 --> <property name="transactionManager" ref="transactionManager"></property> <property name="transactionAttributes"> <!-- 定义事务传播属性 --> <props> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="save*">PROPAGATION_REQUIRED</prop> <prop key="add*">PROPAGATION_REQUIRED</prop> <prop key="remove*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="change*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> <!-- 定义BeanNameAutoProxyCreator --> <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <!-- 指定满足哪些bean自动生成业务代理 --> <property name="beanNames"> <!-- 需要自动创建事务代理的bean --> <list> <value>userService</value>[/code] </list> <!-- 其它需要自动创建事务代理的bean --> </property> <property name="interceptorNames"> <list> <value>transactionInterceptor</value> <!-- 可增加其它的interceptor --> </list> </property> </bean> </beans>
springboot下 shiro + redis 验证后无动作
shiro + redis 由于shiro之前没有用过 , 这次使用也是比较仓促 希望大佬们多多帮组 > 跪谢 可以在redis中看到 session的存储 验证后并不跳转到首页 附上 代码 1. 目录结构 ![图片说明](https://img-ask.csdn.net/upload/201904/26/1556279189_984298.jpg) 2. shiroConfig.java ``` import com.chenzs.common.mapper.RoleMapper; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.crazycake.shiro.RedisCacheManager; import org.crazycake.shiro.RedisManager; import org.crazycake.shiro.RedisSessionDAO; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.Resource; import java.util.LinkedHashMap; import java.util.Map; /** * @author ChenZS */ @Configuration public class ShiroConfig { @Resource private RoleMapper roleMapper; @Bean public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) { System.err.println("ShiroConfiguration.shirFilter() ---> start "); ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); //拦截器. Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>(); // 配置不会被拦截的链接 顺序判断 // filterChainDefinitionMap.put("/css/**", "authc"); // filterChainDefinitionMap.put("/js/**", "authc"); // filterChainDefinitionMap.put("/img/**", "authc"); // filterChainDefinitionMap.put("/components/**", "authc"); // filterChainDefinitionMap.put("/favicon.ico", "authc"); //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了 // filterChainDefinitionMap.put("/logout", "logout"); //<!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了; //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问--> // filterChainDefinitionMap.put("/**", "authc"); // 如果不设置默认会自动寻找Web工程根目录下的"/login"页面 shiroFilterFactoryBean.setLoginUrl("/login"); // // 登录成功后要跳转的链接 shiroFilterFactoryBean.setSuccessUrl("/blog"); //未授权界面; shiroFilterFactoryBean.setUnauthorizedUrl("/404"); filterChainDefinitionMap.put("/static/**", "anon"); // filterChainDefinitionMap.put("/", "perms[admin]"); // filterChainDefinitionMap.put("/user/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); // //从数据库获取 对应角色 // List<Role> list = roleMapper.selectByExample(null); // // for (SysPermissionInit sysPermissionInit : list) { // filterChainDefinitionMap.put(sysPermissionInit.getUrl(), // sysPermissionInit.getPermissionInit()); // } // // shiroFilterFactoryBean // .setFilterChainDefinitionMap(filterChainDefinitionMap); System.out.println("Shiro拦截器工厂类注入成功"); return shiroFilterFactoryBean; } /** * 凭证匹配器 * (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了 * ) * @return */ @Bean public HashedCredentialsMatcher hashedCredentialsMatcher(){ HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); //散列算法:这里使用MD5算法; hashedCredentialsMatcher.setHashAlgorithmName("md5"); //散列的次数,比如散列两次,相当于 md5(md5("")); hashedCredentialsMatcher.setHashIterations(1); return hashedCredentialsMatcher; } @Bean public MyShiroRealm myShiroRealm(){ MyShiroRealm myShiroRealm = new MyShiroRealm(); myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return myShiroRealm; } @Bean public SecurityManager securityManager(){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); //设置realm securityManager.setRealm(myShiroRealm()); // 自定义缓存实现 使用redis securityManager.setCacheManager(cacheManager()); // 自定义session管理 使用redis securityManager.setSessionManager(sessionManager()); return securityManager; } /** * 开启shiro aop注解支持. * 使用代理方式;所以需要开启代码支持; * @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){ AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } /** * cacheManager 缓存 redis实现 * 使用的是shiro-redis开源插件 * * @return */ public RedisCacheManager cacheManager() { RedisCacheManager redisCacheManager = new RedisCacheManager(); redisCacheManager.setRedisManager(redisManager()); return redisCacheManager; } /** * 配置shiro redisManager * 使用的是shiro-redis开源插件 * * @return */ public RedisManager redisManager() { RedisManager redisManager = new RedisManager(); redisManager.setHost("192.168.0.12"); redisManager.setPort(6379); redisManager.setExpire(1800 * 60 *30);// 配置缓存过期时间 redisManager.setTimeout(0); redisManager.setPassword("123456789+"); // redisManager.setPassword(password); return redisManager; } /** * Session Manager * 使用的是shiro-redis开源插件 */ @Bean public DefaultWebSessionManager sessionManager() { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setSessionDAO(redisSessionDAO()); return sessionManager; } // @Bean("sessionManager") // public SessionManager sessionManager(ShiroSessionDao shiroSessionDa){ // DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); // sessionManager.setGlobalSessionTimeout(60 * 60 * 1000); // sessionManager.setSessionValidationSchedulerEnabled(true); // sessionManager.setSessionIdUrlRewritingEnabled(false); // sessionManager.setSessionDAO(shiroSessionDao); // /** 此注释代码 就是将JSESSIONID变成自定义名称 WEBJSESSIONID // sessionManager.setSessionIdCookieEnabled(true); // SimpleCookie cookie = new SimpleCookie("WEBJSESSIONID"); // cookie.setHttpOnly(true); // cookie.setMaxAge(60 * 60 * 1000); // sessionManager.setSessionIdCookie(cookie); **/ // return sessionManager; // } /** * RedisSessionDAO shiro sessionDao层的实现 通过redis * 使用的是shiro-redis开源插件 */ @Bean public RedisSessionDAO redisSessionDAO() { RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); redisSessionDAO.setRedisManager(redisManager()); // // DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); // sessionManager.setGlobalSessionTimeout(60 * 60 * 1000); // sessionManager.setSessionValidationSchedulerEnabled(true); // sessionManager.setSessionIdUrlRewritingEnabled(false); // /** 此注释代码 就是将JSESSIONID变成自定义名称 WEBJSESSIONID */ // sessionManager.setSessionIdCookieEnabled(true); // SimpleCookie cookie = new SimpleCookie("WEBJSESSIONID"); // cookie.setHttpOnly(true); // cookie.setMaxAge(60 * 60 * 1000); // sessionManager.setSessionIdCookie(cookie); return redisSessionDAO; } } ``` ------ 3. MyShiroRealm.java ``` import com.chenzs.common.model.Role; import com.chenzs.common.model.User; import com.chenzs.common.service.RoleService; import com.chenzs.common.service.UserService; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import javax.annotation.Resource; import java.io.Serializable; import java.util.List; /** * @author ChenZS */ public class MyShiroRealm extends AuthorizingRealm{ @Resource private UserService userService; @Resource private RoleService roleService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()"); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); // User user = (User) principals.getPrimaryPrincipal(); // List<Role> roleList = roleService.listRolesByUser(user); // TODO 后续应根据用户id 获取对应的权限,而不是现在的所有权限 ( 现在只有一种权限 --> admin ) List<Role> roleList = roleService.getListRole(); for (Role role : roleList) { authorizationInfo.addRole(role.getRole()); } return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.err.println("MyShiroRealm.doGetAuthenticationInfo() --> 开始权限验证!"); //获取用户的输入的账号. String username = (String) token.getPrincipal(); System.out.println(token.getCredentials()); //通过username从数据库中查找 User对象,如果找到,没找到. //实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法 User user = userService.getUser(username); if (user.getId() == null) { return null; } // User user = response.getData(); if (!user.getStatus()) { throw new LockedAccountException(username + "账号未激活或账号被封禁!"); } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( user, user.getPassword(), getName() ); return authenticationInfo; } } ``` 4. loginController .java ``` import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/login") public class LoginController { private static final String PATH = "login/"; @RequestMapping("") public String index() { return PATH + "index"; } /** * 登录提交 * @param model * @return * @throws Exception */ @PostMapping("/login_info") public String login(@RequestParam(required = true, value = "userName") String userName,@RequestParam(required = true, value = "password") String password, Model model) throws Exception { //1、验证用户名和密码 org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, password); String msg = "OK"; try { subject.login(usernamePasswordToken); // return "myhome/index"; } catch (UnknownAccountException e) { System.err.println("UnknownAccountException -- > 账号不存在:"); msg = "账号不存在!"; } catch (IncorrectCredentialsException e) { System.err.println("IncorrectCredentialsException -- > 密码不正确:"); msg = "密码不正确!"; } catch (LockedAccountException e) { System.err.println("LockedAccountException -- > 账号被锁定"); msg = "账号被锁定!"; } catch (Exception e) { System.err.println(e.getMessage()); } model.addAttribute("msg", msg); // return PATH + "index"; return "myhome/index"; } } ``` wechat: chen1749144759 求大佬 帮助 真的没有赏金了
求助:springboot中接口和实现类不在同一个jar中,@Autowired失败
# 1.demo ## 1-1.接口定义 包名:com.example.demo 接口:ITest ``` package com.example.demo; public interface ITest { void find(); } ``` ## 1.2.接口使用 ``` @Autowired @Qualifier("myTest2") // ←自动注入不同的实现类 private ITest itest; // 调用实现类的方法 itest.find(); ``` ## 1.3.同一jar中定义实现类 ``` package com.example.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class MyTest2 implements ITest { private static final Logger LOGGER = LoggerFactory.getLogger(MyTest2.class); @Override public void find() { LOGGER.info("MyTest2#find"); } } ``` # 2.demo01 在其他jar中定义实现类【**包名相同**】 ``` package com.example.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class MyTest implements ITest { private static final Logger LOGGER = LoggerFactory.getLogger(MyTest.class); @Override public void find() { LOGGER.info("MyTest#find"); } } ``` **注)Springboot入口类:** ``` @SpringBootApplication(scanBasePackages = { "com.example" }) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 然后修改上面【1.2.接口使用】中@Qualifier的实现类,运行后发现: 1.@Qualifier("myTest") -------> 运行失败,错误如下: > *************************** > APPLICATION FAILED TO START > *************************** > > Description: > > Field itest in com.example.demo.MyRunner required a bean of type 'com.example.demo.ITest' that could not be found. > > > Action: > > Consider defining a bean of type 'com.example.demo.ITest' in your configuration. 2.@Qualifier("myTest2") -------> 运行成功
Hibernate查询数据时出现的问题
相关参数:MyEclipse7,MySQL5,Hibernate 3.2,Spring 2.0,Struts 1.2. 问题概述:使用SSH搭建,提供了方法eqField(String field,String value),该方法使用QBC查询,field填写查询字段,value填写值,然后返回该实体的List,库中[字段=‘值’]的实体全部取出。但是在操作中出现了如下异常信息,我试图使用手工写HQL的方式,仍然不好用。 异常信息: org.springframework.orm.hibernate3.HibernateSystemException: IllegalArgumentException occurred calling getter of com.kupid.domain.Jbdata.id; nested exception is org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.kupid.domain.Jbdata.id 相关代码段: 项目实体使用Hibernate的反向工程从DB自动生成。 Jbcomment实体,其中有属性Jbdata,是自定义的一个BEAN。 [code="java"] public class Jbcomment implements java.io.Serializable { // Fields private String id; private Jbfield jbfield; private Jbdata jbdata; private String name; private Integer flag; private Date creatdate; private Date lastupdate; private String pre1; private String pre2; private String pre3; [/code] 实体Jbdata [code="java"] public class Jbdata implements java.io.Serializable { // Fields private String id; private Jbtype jbtype; private String name; private Date createrdate; private Date lastdate; private Integer flag; [/code] 在实体Jbcomment的操作实现类JbcommentDaoImpl中,提供了eqField方法,该类代码片段如下: [code="java"] public class JbcommentDaoImpl extends BaseDaoImpl<Jbcomment,String> implements JbcommentDao { public List<Jbcomment> findAll() { return (List<Jbcomment>) ht.execute(new HibernateCallback() { public Object doInHibernate(Session s) throws HibernateException, SQLException { Criteria c = s.createCriteria(Jbcomment.class); c.add(Restrictions.like("id","%")); return c.list(); } }); } public List<Jbcomment> eqField(final String field,final String value) { return (List<Jbcomment>) ht.execute(new HibernateCallback() { public Object doInHibernate(Session s) throws HibernateException, SQLException { Criteria c = s.createCriteria(Jbcomment.class); c.add(Restrictions.eq(field,value)); return c.list(); } }); } [/code] 在对应的Service中注入了上述JbcommentDaoImpl,其中getField_eq方法无任何差异的调用了eqField。 [code="java"] public class JbcommentServiceImpl implements JbcommentService { private JbcommentDao jbcommentDao; public List<Jbcomment> getField_eq(String field,String value) { return jbcommentDao.eqField(field, value); } [/code] 然后,某个操作调用了一个showDataDetail.do,其片段如下: [code="java"] public class ShowDataDetail extends Action { private JbcommentServiceImpl cmtsi; private JbfieldServiceImpl fieldsi; private JbdataServiceImpl datasi; public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ System.out.println("Create a detail"); try { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String dataId=request.getParameter("id"); String keywords=request.getParameter("keywords"); List<Jbcomment> list=cmtsi.getField_eq("jbdata", dataId); [/code] 在最后一行,取list的时候,异常出现了。 希望得到一个详细的,明确的分析。若是如:“详见XX书”,“答案可访问XX网”,“自己去看API”等回答,就不劳烦您了。 谢谢指教。 关于源码: 源码以问题附件的形式上传了,因为jar包超过了附件的10M限制而被剔除。 源码内包名domain,persist,service,actions,顾名思义不做多解释了。 jar包移出后传至Rayfile了,其下载地址为 http://www.rayfile.com/files/e8680f6e-c838-11de-ab98-0014221b798a/ 数据库以SQL校本形式导出,本人常用MySQL-Administrator,所以先用该工具导出,但由于该工具导出的脚步的DB倒回在其他工具中可能存在编码问题,于是又用Navicat导出了一份通用性好的 sql脚本.
我在做事务设置的时候产生下面的错误!!!
严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'serverdataSource': Bean with name 'serverdataSource' has been injected into other beans [serversessionFactory] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:498) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:220) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:729) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:381) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4342) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:926) at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:889) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1149) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053) at org.apache.catalina.core.StandardHost.start(StandardHost.java:719) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:516) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:578) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) 2009-10-15 16:50:26 org.apache.catalina.core.StandardContext start 严重: Error listenerStart 2009-10-15 16:50:26 org.apache.catalina.core.StandardContext start 严重: Context [/glcollege] startup failed due to previous errors 2009-10-15 16:50:26 org.apache.catalina.core.ApplicationContext log 我的设置如下: <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <!-- the transactional semantics... --> <tx:attributes> <!-- all methods starting with 'get' are read-only --> <tx:method name="get*" read-only="true"/> <tx:method name="list*" read-only="true"/> <!-- other methods use the default transaction settings (see below) --> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="ServiceOperation" expression="execution(* com.gl.service.impl.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="ServiceOperation"/> </aop:config> [b]问题补充:[/b] 请明示,我比较初级,很想你能再说得明白一点, [b]问题补充:[/b] <?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: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-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"> </property> <property name="url" value="jdbc:oracle:thin:202.118.121.112:1521:orcl"> </property> <property name="username" value="scott"></property> <property name="password" value="gl"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="mappingResources"> <list> <value>com/gl/model/Score.hbm.xml</value> <value>com/gl/model/Userpassword.hbm.xml</value> <value>com/gl/model/Xuanke.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> <prop key="show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.jdbc.batch_size">20</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--<bean id ="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"> <property name="transactionManager"> <ref bean="transactionManager"/> </property> </bean> --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- the transactional semantics... --> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="*" read-only="true"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="ServiceOperation" expression="execution(* com.gl.service.impl.*.*(..))"/> <aop:advisor pointcut-ref="ServiceOperation" advice-ref="txAdvice"/> </aop:config> <!--<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> 事务拦截器bean需要依赖注入一个事务管理器 <property name="transactionManager" ref="transactionManager"/> <property name="transactionAttributes"> 下面定义事务传播属性 <props> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> 定义BeanNameAutoProxyCreator <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> 指定对满足哪些bean name的bean自动生成业务代理 <property name="beanNames"> 下面是所有需要自动创建事务代理的bean <list> <value>mgr</value> <value>cmgr</value> <value>xmgr</value> </list> 此处可增加其他需要自动创建事务代理的bean </property> 下面定义BeanNameAutoProxyCreator所需的事务拦截器 <property name="interceptorNames"> <list> 此处可增加其他新的Interceptor <value>transactionInterceptor</value> </list> </property> </bean> --><bean id="userpasswordDao" class="com.gl.dao.hibernate.UserpasswordDaoHibernate" abstract="false" lazy-init="default" autowire="default" dependency-check="default"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean id="mgr" class="com.gl.service.impl.UserpasswordManagerimpl" abstract="false" lazy-init="default" autowire="default" dependency-check="default"> <property name="userpasswordDao"> <ref bean="userpasswordDao" /> </property> </bean> <bean id="LoginAction" class="com.gl.action.LoginAction" abstract="false" scope="prototype" lazy-init="default" autowire="default" dependency-check="default"> <property name="mgr"> <ref bean="mgr" /> </property> </bean> <bean id="scoreDao" class="com.gl.dao.hibernate.ScoreDaoHibernate" abstract="false" lazy-init="default" autowire="default" dependency-check="default"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean id="cmgr" class="com.gl.service.impl.ScoreManagerimpl" abstract="false" lazy-init="default" autowire="default" dependency-check="default"> <property name="scoreDao"> <ref bean="scoreDao" /> </property> </bean> <bean id="ShowAction" class="com.gl.action.ShowActon" abstract="false" lazy-init="default" autowire="default" dependency-check="default" scope="prototype"> <property name="cmgr"> <ref bean="cmgr" /> </property> </bean> <bean id="xuankeDao" class="com.gl.dao.hibernate.XuankeDaoHibernate" abstract="false" lazy-init="default" autowire="default" dependency-check="default"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> <property name="pageSize" value="5" /> </bean> <bean id="xuankemanager" class="com.gl.service.impl.XuankeManagerimpl" abstract="false" lazy-init="default" autowire="default" dependency-check="default"> <property name="xuankeDao"> <ref bean="xuankeDao" /> </property> </bean> <bean id="XuankeAction" class="com.gl.action.XuankeAction" abstract="false" lazy-init="default" autowire="default" dependency-check="default" scope="prototype"> <property name="xuankemanager"> <ref bean="xuankemanager" /> </property> </bean> <bean id="courseaction" class="com.gl.action.courseaction" abstract="false" lazy-init="default" autowire="default" dependency-check="default" scope="prototype"> <property name="xuankemanager"> <ref bean="xuankemanager" /> </property> </bean> </beans> [b]问题补充:[/b] 是啊,我前一段时间做的这个项目,今天突然想加上事务可是就不行,也不知道到哪里的问题, [b]问题补充:[/b] 在配置文件中,<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> 这种方式我是注释掉的,应该不会冲突啊! [b]问题补充:[/b] 我删掉了多余的注释东西,可是,还是报那个错,伤脑筋啊!!! [b]问题补充:[/b] 请指点!! [b]问题补充:[/b] 改了,可是,还是报那个错误! [b]问题补充:[/b] 我找到问题的地方了,是因为我有两个applicationcontext.xml配置文件,而在两个配置文件中我都写了事务的设置,所以才报这个错误。如果有多个applicationcontext.xml文件的话,只需要在其中一个设置事务即可。希望不要犯我这样的错误了! 同时在这里谢谢[size=medium]lovewhzlq[/size]的分析,你的分析是正确的,希望以后可以和你继续交流,能留下你的QQ吗,在此结贴给分!
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载    点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量 path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、PDF搜索网站推荐 对于大部
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入  假设现有4个人
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 欢迎 改进 留言。 演示地点跳到演示地点 html代码如下`&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;music&lt;/title&gt; &lt;meta charset="utf-8"&gt
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐厅的约会 餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”我楞了一下,心里想女朋友今天是怎么了,怎么突然问出这么专业的问题,但做为一个专业人士在女朋友面前也不能露怯啊,想了一下便说:“我先给你讲讲我前同事老王的故事吧!” 大龄程序员老王 老王是一个已经北漂十多年的程序员,岁数大了,加班加不动了,升迁也无望,于是拿着手里
经典算法(5)杨辉三角
写在前面: 我是 扬帆向海,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。 这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。 用知识改变命运,让我们的家人过上更好的生活。 目录一、杨辉三角的介绍二、杨辉三角的算法思想三、代码实现1.第一种写法2.第二种写法 一、杨辉三角的介绍 百度
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看
SQL-小白最佳入门sql查询一
一 说明 如果是初学者,建议去网上寻找安装Mysql的文章安装,以及使用navicat连接数据库,以后的示例基本是使用mysql数据库管理系统; 二 准备前提 需要建立一张学生表,列分别是id,名称,年龄,学生信息;本示例中文章篇幅原因SQL注释略; 建表语句: CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // dosho
【图解经典算法题】如何用一行代码解决约瑟夫环问题
约瑟夫环问题算是很经典的题了,估计大家都听说过,然后我就在一次笔试中遇到了,下面我就用 3 种方法来详细讲解一下这道题,最后一种方法学了之后保证让你可以让你装逼。 问题描述:编号为 1-N 的 N 个士兵围坐在一起形成一个圆圈,从编号为 1 的士兵开始依次报数(1,2,3…这样依次报),数到 m 的 士兵会被杀死出列,之后的士兵再从 1 开始报数。直到最后剩下一士兵,求这个士兵的编号。 1、方
致 Python 初学者
文章目录1. 前言2. 明确学习目标,不急于求成,不好高骛远3. 在开始学习 Python 之前,你需要做一些准备2.1 Python 的各种发行版2.2 安装 Python2.3 选择一款趁手的开发工具3. 习惯使用IDLE,这是学习python最好的方式4. 严格遵从编码规范5. 代码的运行、调试5. 模块管理5.1 同时安装了py2/py35.2 使用Anaconda,或者通过IDE来安装模
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,
程序员:我终于知道post和get的区别
IT界知名的程序员曾说:对于那些月薪三万以下,自称IT工程师的码农们,其实我们从来没有把他们归为我们IT工程师的队伍。他们虽然总是以IT工程师自居,但只是他们一厢情愿罢了。 此话一出,不知激起了多少(码农)程序员的愤怒,却又无可奈何,于是码农问程序员。 码农:你知道get和post请求到底有什么区别? 程序员:你看这篇就知道了。 码农:你月薪三万了? 程序员:嗯。 码农:你是怎么做到的? 程序员:
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
      11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI 算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC
【技巧总结】位运算装逼指南
位算法的效率有多快我就不说,不信你可以去用 10 亿个数据模拟一下,今天给大家讲一讲位运算的一些经典例子。不过,最重要的不是看懂了这些例子就好,而是要在以后多去运用位运算这些技巧,当然,采用位运算,也是可以装逼的,不信,你往下看。我会从最简单的讲起,一道比一道难度递增,不过居然是讲技巧,那么也不会太难,相信你分分钟看懂。 判断奇偶数 判断一个数是基于还是偶数,相信很多人都做过,一般的做法的代码如下
日均350000亿接入量,腾讯TubeMQ性能超过Kafka
整理 | 夕颜出品 | AI科技大本营(ID:rgznai100) 【导读】近日,腾讯开源动作不断,相继开源了分布式消息中间件TubeMQ,基于最主流的 OpenJDK8开发的
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
面试官如何考察你的思维方式?
1.两种思维方式在求职面试中,经常会考察这种问题:北京有多少量特斯拉汽车? 某胡同口的煎饼摊一年能卖出多少个煎饼? 深圳有多少个产品经理? 一辆公交车里能装下多少个乒乓球? 一
so easy! 10行代码写个"狗屁不通"文章生成器
前几天,GitHub 有个开源项目特别火,只要输入标题就可以生成一篇长长的文章。背后实现代码一定很复杂吧,里面一定有很多高深莫测的机器学习等复杂算法不过,当我看了源代码之后这程序不到50
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的 回答 - Bravo Yeung,获得该问题下回答中得最高赞(236赞和1枚专业勋章),对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalk
MySQL数据库总结
文章目录一、数据库简介二、MySQL数据类型(5.5版本)三、Sql语句(1)Sql语句简介(2)数据定义语言DDLcreate,alter,drop(3)数据操纵语言DMLupdate,insert,delete(4)数据控制语言DCLgrant,revoke(5)数据查询语言DQLselect(6)分组查询与分页查询group by,limit四、完整性约束(单表)五、多表查询六、MySQL数
记一次腾讯面试:进程之间究竟有哪些通信方式?如何通信? ---- 告别死记硬背
有一次面试的时候,被问到进程之间有哪些通信方式,不过由于之前没深入思考且整理过,说的并不好。想必大家也都知道进程有哪些通信方式,可是我猜很多人都是靠着”背“来记忆的,所以今天的这篇文章,讲给大家详细着讲解他们是如何通信的,让大家尽量能够理解他们之间的区别、优缺点等,这样的话,以后面试官让你举例子,你也能够顺手拈来。 1、管道 我们来看一条 Linux 的语句 netstat -tulnp | gr...
20行Python代码爬取王者荣耀全英雄皮肤
引言 王者荣耀大家都玩过吧,没玩过的也应该听说过,作为时下最火的手机MOBA游戏,咳咳,好像跑题了。我们今天的重点是爬取王者荣耀所有英雄的所有皮肤,而且仅仅使用20行Python代码即可完成。 准备工作 爬取皮肤本身并不难,难点在于分析,我们首先得得到皮肤图片的url地址,话不多说,我们马上来到王者荣耀的官网: 我们点击英雄资料,然后随意地选择一位英雄,接着F12打开调试台,找到英雄原皮肤的图片
相关热词 c# plc s1200 c#里氏转换原则 c# 主界面 c# do loop c#存为组套 模板 c# 停掉协程 c# rgb 读取图片 c# 图片颜色调整 最快 c#多张图片上传 c#密封类与密封方法
立即提问