Spring 注入为空

在一个SSH的项目中遇到一个问题,我有一个dao的接口BaseJdbcDao,和一个dao的实现类BaseJdbcDaoImpl,实现类已经通过注解提交给容器进行管理,然后有一个工具类MailHelper想通过自动装配载入dao的实现类,可是每次都没有装配成功,代码如下,请教各位:
[code="java"]
package base;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.support.rowset.SqlRowSet;
public interface BaseJdbcDao {

public abstract List queryForList(String sql);

public abstract int queryForInt(String sql);

public abstract SqlRowSet queryForRowSet(String sql);

public abstract int update(String sql);

public abstract Map queryForMap(String sql);

public abstract void delete(String sql);

public abstract void insert(String sql);

}
[/code]
[code="java"]
package base.impl;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import base.BaseJdbcDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("basejdbcdao")
public class BaseJdbcDaoImpl implements BaseJdbcDao {

private  JdbcTemplate jdbcTemplate;

public  JdbcTemplate getJdbcTemplate() {
    return jdbcTemplate;
}

@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}

public List queryForList(String sql){
    System.out.println(sql);
       return this.getJdbcTemplate().queryForList(sql);
    }

public int queryForInt(String sql){
    System.out.println(sql);
    return this.getJdbcTemplate().queryForInt(sql);
}

public SqlRowSet queryForRowSet(String sql){
    System.out.println(sql);
    return this.getJdbcTemplate().queryForRowSet(sql);
}

public int update(String sql){
    System.out.println(sql);
    return this.getJdbcTemplate().update(sql);
}

public Map queryForMap(String sql){
    System.out.println(sql);
    return this.getJdbcTemplate().queryForMap(sql);
}

public void delete(String sql){
    System.out.println(sql);
    this.getJdbcTemplate().update(sql);
}

public void insert(String sql){
    System.out.println(sql);
    this.getJdbcTemplate().execute(sql);
}

}
[/code]
[code="java"]package util;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import java.util.Date;
import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import util.ByteArrayDataSource;
import javax.mail.PasswordAuthentication;
import base.BaseJdbcDao;
import base.impl.BaseJdbcDaoImpl;

public class MailHelper {

@Autowired
@Qualifier("basejdbcdao")
private BaseJdbcDao dao;

private String email;
private String mobile;
private String school;
private String name;
private String remark;
private String appstr; 

public MailHelper(String school,String name,String mobile,String email,String remark,String appstr){
    this.email =  email;
    this.mobile = mobile;
    this.school = school;
    this.name = name;
    this.remark = remark;
    this.appstr = appstr;
}

public MailHelper(){};

public void sendMail(){
   this.insertData(school,name,mobile,email,remark,appstr);
}



/**
 * 帐号申请的功能
 * @param template
 * @param pschool
 * @param pname
 * @param pmobile
 * @param pemail
 * @param premark
 */
public void insertData(String pschool,String pname,String pmobile,String pemail,String premark,String appstr){
    String email = changeContent( pemail);
    String mobile = changeContent( pmobile);
    String school =changeContent (pschool);
    String name =changeContent (pname);
    String remark = changeContent (premark);
    String to  = "test@163.com";
    String subject = "申请";
    StringBuilder sb = new StringBuilder("insert into maillist(linkman,school,mobile,mail,remark)values('"+name+"','"+school+"','"+mobile+"','"+email+"','"+remark+"')");
    dao.update(sb.toString());
    remark = "内容略。。";
    this.send(  to, subject, remark);
}

/**
 * Sending a mail with given values.<br>
 * content parameter means the main email text,it refers to a html file. 
 * 
 * @param smtpServer
 * @param to
 * @param from
 * @param subject
 * @param content
 * @param emailUsername
 * @param emailUserpass
 * @author WYQ
 */ 
private String send(String to,String subject,String content) {
    try {
        HashMap<String,String> map = readParamters();
        String smtpserver = map.get("smtpserver");
        String publicaccount = map.get("publicaccount");
        String publicpwd = map.get("publicpwd");
        String from = map.get("publicmail");

        Properties props = System.getProperties();
        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.starttls.enable","false");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpserver);

        Session session = null;
        session = Session.getDefaultInstance(props,new PasswordAuthenticator(publicaccount,publicpwd));

        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(  to, false));
        msg.setSubject(subject);
        msg.setDataHandler(new DataHandler(new ByteArrayDataSource(content,"text/html; charset=\"utf-8\"")));
        msg.setHeader("X-Mailer", "XML-Mail");
        msg.setSentDate(new Date());
        // -- Send the message --
        Transport.send(msg);
        return "success";
    } catch (Exception ex) {
        return "Error" + ex;
    }
}


private HashMap<String,String> readParamters(){
    HashMap<String,String> map = new HashMap<String,String>();
    Properties properties =new Properties();
    try {
           properties.load(MailHelper.class.getClassLoader().getResourceAsStream("mail.properties"));
           map.put("smtpserver",   properties.getProperty("smtpserver"));
           map.put("publicmail",   properties.getProperty("publicmail"));
           map.put("publicaccount",   properties.getProperty("publicaccount"));
           map.put("publicpwd",   properties.getProperty("publicpwd"));
          } catch (IOException e) {
           e.printStackTrace();
     }
      return map;
}

}

class PasswordAuthenticator extends Authenticator {
private String username;
private String password;

public PasswordAuthenticator(String username, String password) {
    this.username = username;
    this.password = password;
}
protected PasswordAuthentication  getPasswordAuthentication() {
    return new PasswordAuthentication (username, password);
}

}

[/code]
然后我在struts的action类中调用MailHelper的send方法进行邮件发送时,打印的dao总是为空,action的代码是:
[code="java"]
/**
* 帐号申请-邮件发送
* @return
*/
public String sendMail(){
MailHelper mh = new MailHelper();
mh.sendMail();
success = true;
return SUCCESS;
}
[/code]
spring的自动扫描和注解配置已经开启,也已经把dao的package路径和MailHelper的package路径加入到基类中了,
[code="java"]

[/code]
现在就是弄不明白,为什么通过new出来的MailHelper对象中注入的dao总是为空呢。

3个回答

给你点代码片段,参考下:
[code="java"]
// dao
public class BaseDaoHibernate extends
HibernateDaoSupport implements BaseDao {
protected Class persistentClass;

@Autowired
public void setSessionFactory0(SessionFactory sessionFactory) {
    super.setSessionFactory(sessionFactory);
}

@Repository("authorizeDao")
public class AuthorizeDaoHibernate extends BaseDaoHibernate
implements AuthorizeDao {
private Criteria getAuthorizeCriteria(Authorize auth) {
Criteria crit = getCriteria();
Example example = Example.create(auth);
example.enableLike(MatchMode.ANYWHERE);
crit.add(example);
if (auth.getDate_s() != null) {
crit.add(Restrictions.ge("createDate", auth.getDate_s()));
}
if (auth.getDate_e() != null) {
crit.add(Restrictions.le("createDate", auth.getDate_e()));
}
return crit;
}

// service
@Service("authorizeService")
public class AuthorizeServiceImpl implements AuthorizeService {
@Autowired
private AuthorizeDao authorizeDao;

public Authorize getAuthorizeByAuthId(Long authId) {
    return authorizeDao.getById(authId);
}

public List<Authorize> findAll() {
    return authorizeDao.findAll();
}

//action
@SuppressWarnings("serial")
public class AdminAction extends AuthAction {
private SiteBackGroudUser user;
private Long keyId;

private List<Authorize> auths;

private Page page;

@Autowired
private SiteBackGroudUserService siteBackGroudUserService;

@Autowired
private AuthorizeService authorizeService;

[/code]
applicationContext.xml
[code="xml"]
<?xml version="1.0" encoding="UTF-8"?>

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<!-- ========================= RESOURCE DEFINITIONS ========================= -->

<!-- Configurer that replaces ${...} placeholders with values from a properties 
    file -->
<!-- (in this case, JDBC-related settings for the dataSource definition 
    below) -->
<context:property-placeholder
    location="classpath:jdbc.properties,classpath:chinapay_conf.properties,classpath:unionpay_conf.properties" />

<!-- Uses Apache Commons DBCP for connection pooling. See Commons DBCP documentation 
    for the required JAR files. Alternatively you can use another connection 
    pool such as C3P0, similarly configured using Spring. -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" />



<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
    p:dataSource-ref="dataSource">
    <property name="packagesToScan" value="com.yintong.model" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
            <prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
            <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
            <!-- 缓存配置 -->
            <prop key="hibernate.cache.provider_class">org.hibernate.cache.OSCacheProvider</prop>
            <prop key="hibernate.cache.use_query_cache">true</prop>
            <prop key="hibernate.cache.use_second_level_cache">true</prop>
            <prop key="hibernate.search.default.directory_provider">org.hibernate.search.store.FSDirectoryProvider
            </prop>
            <prop key="hibernate.search.default.indexBase">E:/indexes
            </prop>
        </props>
    </property>
    <property name="eventListeners">
        <map>
            <entry key="merge">
                <bean
                    class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener" />
            </entry>
        </map>
    </property>
</bean>

<!-- Transaction manager for a single Hibernate SessionFactory (alternative 
    to JTA) -->
<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager"
    p:sessionFactory-ref="sessionFactory" />


<!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->

<!-- Activates various annotations to be detected in bean classes: Spring's 
    @Required and @Autowired, as well as JSR 250's @Resource. -->
<context:annotation-config />
<context:component-scan
    base-package="com.dao.hibernate,
    com.service.impl," />

<!-- Instruct Spring to perform declarative transaction management automatically 
    on annotated classes. -->
<tx:annotation-driven />

<!-- Exporter that exposes the Hibernate statistics service via JMX. Autodetects 
    the service MBean, using its bean name as JMX object name. -->
<context:mbean-export />


[/code]

spring和struts2的结合不需要配置,因为struts默认 spring 自动注入,只要保持你声明的@Service("authorizeService")中的名称与action中该对象的变量名一样就行。

你这样当然不可以了。你应该将MailHelper对象注入到你的action类中,而不是new一个出来。

spring自动装载也是将其类的实例装载到自己的容器中,也就是所谓的上下文中(context).对象的创建都是托管给spring容器的。使用new时当然得不到其对象及其对象以来的dao了。

你可以在你的action中声明一个MailHelper,然后提供其自动注入,并将你的MailHelper标注为一个容器@Resource,让spring管理struts,这样你就可以直接MailHelper而不需要new了。否则你只能读取spring的applicationContext.xml拿到AnnotationConfigApplicationContext对象使用getBean获取MailHelper实例了。

new当然不行了,单纯new的话不用spring管理的话,是不会理会注入啊 注解之类的

总之不是这样玩的 你用new就是你玩你自己的根本没告诉spring这个大管家

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
大哥们帮忙看一个Spring注入为空的问题。。。在线请教。。。
我在spring的配置文件中构造了两个bean,内容如下: <!-- 定义调度对象 --> <bean id="Scheduler" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" > </bean> <bean id="AddJob" class="com.dhcc.scheduler.action.AddAction"> <property name="scheduler"> <ref local="Scheduler"/> </property> </bean> 下面的bean中有一个属性时要用上面得bean来注入的。。。 请看我AddAction中的内容: import org.quartz.impl.StdScheduler;//导入的包 private StdScheduler scheduler;//属性声明 //get,set方法。。。 public StdScheduler getScheduler() { return scheduler; } public void setScheduler(StdScheduler scheduler) { this.scheduler = scheduler; } 为什么调用scheduler时,报scheduler为空的错呢??? [b]问题补充:[/b] 项目部署在tomcat中,启动tomcat不就已经完成加载和注入了吗?? 以下是报错的信息: 严重: Servlet.service() for servlet default threw exception java.lang.NullPointerException at com.dhcc.scheduler.action.AddAction.execute(AddAction.java:138) 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:585) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:404) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:267) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:229) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:221) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:150) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:123) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:184) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:105) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:83) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:207) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:74) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:127) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:107) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:206) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:115) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:143) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:121) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:170) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:123) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:50) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:504) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:421) 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:191) 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:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:595) 使用这句话测试,始终打印scheduler为空。 if(scheduler==null){ System.out.println("scheduler为空"); return ERROR; }
spring 注入时 子类父类注入 后子类属性为空
有这样的结构设计类: 父类: package com.company.name.parent; public class CustomerInfoBO{ private XXXDao xXXDao; //xXXDao setter,getter } 子类: package com.company.name.children; public class CustomerInfoBO extends com.company.name.parent.CustomerInfoBO{ private XXXDao xXXDao; //xXXDao setter,getter // 此时 getter 方法会自动加上 @Override 注释,而且子类中无法调用 xXXDao.execMethod() 方法,报空指针。 基本的描述就是,子类和父类的名称属性名称都一样, 这样的话,子类spring注入的时候,不会把自己类中对应的属性自动注入。 求这样的子类父类同名、属性也同名的解决方案。
spring注入空指针问题
找了一圈还是不行,只能拜托各位了。 action能获取到userService,一样的写法,但这里获取不到,action里也能获取到quartzJob,而且这样获取userService就能够被注入进quartzJob中。 扫描是<context:component-scan base-package="*"/>; 下附代码,空指针出在调用userService里的方法行处,应该说的很清楚了。 普通类: @Component(value="quartzJob") @Scope("prototype") public class QuartzJob implements Job,Serializable { @Autowired private UserService userService; public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; }
spring注入jdbcTemplate时一直为空指针,求大牛指导
已经在spring配置文件中配置了jdbcTemplate的bean,但是在测试类中jdbcTemlpate的注入报空指针 ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-- 配置spring的jdbcTemplate--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 设置spring扫包路径 --> <context:component-scan base-package="com.hzbckj.spring" /> <!-- 导入资源文件 --> <context:property-placeholder location="db.properties" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="driverClass" value="${driverClass}"></property> </bean> </beans> ``` 这是spring配置文件 ``` package com.hzbckj.spring.test; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; /** * Created by jackson on 2017/2/6. */ @Component public class dataSourceTest { @Resource(name = "jdbcTemplate") private JdbcTemplate jdbcTemplate; public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Test public void testJdbc(){ // ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); // JdbcTemplate jdbcTemplate = (JdbcTemplate)ctx.getBean("jdbcTemplate"); String sql = "INSERT INTO user(name, balance) values('Jonn', 200)"; jdbcTemplate.execute(sql); } } ``` 这是使用的地方 执行时jdbcTemplate一直报空
ssh2整合 spring 注入对象为空
在tomact服务启动之后我在Action里对象set方法 打印出对象 证明是注入进去的 ,, 当我调用Action里面对象的时候 就提示我空指针异常 如果使用getBean 的话是可以得到对象的 web.xml [code="java"][/code] <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!-- OpenSessionInView的处理 --> <filter> <filter-name>openSessionInView</filter-name> <filter-class> org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactorydao</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInView</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> applicationContext.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:context="http://www.springframework.org/schema/context" 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.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.pwd}"></property> <property name="maxIdle" value="${jdbc.maxIdleTime}"></property> <property name="maxActive" value="${jdbc.maxPoolSize}"></property> </bean> <bean id="sessionFactorydao" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mappingDirectoryLocations"> <list> <value>classpath:/entity/</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.SQLServerDialect <!-- hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect --> hibernate.show_sql=true </value> </property> </bean> <bean id="p" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list><value>classpath:/jdbc.properties</value></list> </property> </bean> <bean id="txManage" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactorydao" /> </bean> <tx:advice id="TxtransactionManage" transaction-manager="txManage"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="userDaosearch" expression="execution( * ouyang.UserService.*.*(..))" /> <aop:advisor advice-ref="TxtransactionManage" pointcut-ref="userDaosearch" /> </aop:config> <bean id="spring" class="util.SpringUtil" /> <bean id="UserDao" class="testDAO.UserDao"> <property name="sessionFactory" ref="sessionFactorydao" /> </bean> <bean id="UserService" class="UserService.UserService"> <property name="userDao" ref="UserDao" /> </bean> <bean id="userAction" class="Action.UserAction"> <property name="userService" ref="UserService" /> </bean> </beans> UserAction package Action; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import org.apache.xbean.spring.context.ClassPathXmlApplicationContext; import org.springframework.context.ApplicationContext; import org.springframework.web.struts.ActionSupport; import testDAO.IUserDao; import UserService.IUserService; import UserService.UserService; public class UserAction extends ActionSupport{ IUserService userService; public void setUserService(IUserService userService) { System.out.println("注入进来了"); this.userService = userService; } public IUserService getUserService() { return userService; } public String login(){ HttpServletRequest request = ServletActionContext.getRequest(); String name = request.getParameter("name"); String pwd = request.getParameter("pwd"); //ApplicationContext app= new ClassPathXmlApplicationContext("applicationContext.xml"); //userService =(UserService)app.getBean("UserService"); System.out.println(userService==null); if(userService.Login(name, pwd)){ request.setAttribute("success", "登陆成功"); }else{ request.setAttribute("success", "登陆失败"); } return "index"; } }
Spring 注解注入 SessionFactory 空指针异常
# Spring 注解注入 SessionFactory 空指针异常 条件一 applicationContext.xml文件已经配置了SessionFactory ``` <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 引用上面的dataSource配置数据库 --> <property name="dataSource"> <ref bean="dataSource" /> </property> <!-- Hibernate的一些属性配置 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><!-- Hibernate的配置方言 --> <prop key="hibernate.show_sql">true</prop><!-- Hibernate生成的sql语句是否显示 --> </props> </property> <property name="mappingResources"> <list> <value>com/bigfire/entity/Sale.hbm.xml</value> </list> </property> ``` 条件二 SessionFactory 已经成功注入到Spring容器中, ApplicationContext act=new ClassPathXmlApplicationContext("applicationContext.xml"); String[] str=act.getBeanDefinitionNames(); for (String string : str) { System.out.println("..."+string); } ![图片说明](https://img-ask.csdn.net/upload/201808/27/1535361242_671235.png) 这个问题我百度了两天了,有些方法也都试过了,哪位同学解决了麻烦给分享下解决的办法,谢谢了
Spring bean注入 获取为空
<!--applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/db_xyd?useUnicode=true&amp;amp;amp;amp;amp;amp;characterEncoding=utf-8-"> </property> <property name="username" value="root"></property> <property name="password" value="1234"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> <!-- org.hibernate.dialect.SQLServerDialect--> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="mappingResources"> <list> <value>com/model/TDictionary.hbm.xml</value> </list> </property> </bean> <!-- dictionary --> <bean id="TDictionaryDAO" class="com.dao.TDictionaryDAO"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean id="dictionaryAction" class="com.action.dictionaryAction" scope="prototype"> <property name="dictionaryDAO"> <ref bean="TDictionaryDAO" /> </property> </bean> </beans> package com.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.model.TDictionary; public class TDictionaryDAO extends HibernateDaoSupport { private static final Log log = LogFactory.getLog(TDictionaryDAO.class); public void save(TDictionary transientInstance) { log.debug("saving TDictionary instance"); try { getHibernateTemplate().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public static TDictionaryDAO getFromApplicationContext(ApplicationContext ctx) { return (TDictionaryDAO) ctx.getBean("TDictionaryDAO"); } } package com.action; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.dao.TDictionaryDAO; import com.model.TDictionary; import com.opensymphony.xwork2.ActionSupport; public class dictionaryAction extends ActionSupport { private int OID; private String willtake; private TDictionaryDAO dictionaryDAO; public String dictionaryAdd() { TDictionary dict=new TDictionary(); dict.setOID(OID); dict.setL_key(100000); dict.setVc_value(willtake); dict.setVc_caption("vc_caption"); //这里报空指针异常,是dictionaryDAO空 dictionaryDAO.save(dict); return "success"; } public TDictionaryDAO getDictionaryDAO() { return dictionaryDAO; } public void setDictionaryDAO(TDictionaryDAO dictionaryDAO) { this.dictionaryDAO = dictionaryDAO; } }
spring注入失败
最近想把以前的项目增加的service托给spring处理 [code="java"] <bean id="userBusiness" class="com.*.service.impl.UserBusinessImpl"> <property name="userDAL" ref="userDao"></property> </bean> <bean id="userDao" class="com.*.dao.impl.UserDALImpl"> </bean> [/code] UserDALImpl是原先先好的DAO层的类,有自己的查询数据库的一些实现.我现在只想把userDao注入到service层里面处理 [code="java"] UserBusinessImpl private UserDAL userDAL; public void setUserDAL(UserDAL userDAL) { this.userDAL = userDAL; } [/code] 感觉就是简单的注入,还是失败. spring不熟,各位指点下. [b]问题补充:[/b] *号是我项目的 名称,我没写出来,其实是有路径的 UserDALImpl是实现UserDAL 接口 [b]问题补充:[/b] 没有报错信息. 只是在执行 [code="java"] UserBusinessImpl.java private UserDAL userDAL; public void setUserDAL(UserDAL userDAL) { this.userDAL = userDAL; } public Person getUserFromEXTNO(String extNo) throws Exception { return userDAL.getUserFromEXTNO(extNo); } [/code] [code="java"] public class UserDALImpl extends BaseDAL implements UserDAL { // 初始化Log private Logger logger = Logger.getLogger(UserDALImpl.class); public UserDALImpl() throws Exception { } public Person getUserFromEXTNO(String extNo) throws Exception { 执行SQL } [/code] spring配置文件就这2个 [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: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/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <bean id="userBusiness" class="com.ccsee.happytrip.service.impl.UserBusinessImpl"> <property name="userDAL" ref="userDao"></property> </bean> <bean id="userDao" class="com.ccsee.happytrip.dao.impl.UserDALImpl"> </bean> </beans> [/code] 报的异常是在执行getUserFromEXTNO方法时候抛空指针,也就是注入失败,没把dao注入到service层中 [b]问题补充:[/b] [code="java"] UserDALImpl对象看看调用时是不是new的呢?? 如果是那就肯定错了 UserDALImpl 也得用spring注入 或者用applicationConexst.getbean取[/code] UserDALImpl对象我是打算把他注入到UserBusinessImpl中去的,在UserBusinessImpl中是用set接口进去的 至于UserDALImpl本身有自己的JDBC连接池以及一系列的操作. [b]问题补充:[/b] [code="java"] 不对吧 你是已经从bean工程里取出来了 然后执行dao的方法时候报的错么? 如果取出来了 就证明你配置没错 。。。。。你把堆栈信息贴过来 我看看是在哪掉用的时候出的空指针 [/code] 配置文件的写法应该是对的,服务器启动正常, 但是没有注入成功.在执行到UserBusinessImpl的时候抛空指针, [2009-12-04 17:08:18,125]-ERROR (UserLoginAction.java:93)| java.lang.NullPointerException at com.ccsee.happytrip.service.impl.UserBusinessImpl.getUserFromEXTNO(Us erBusinessImpl.java:67) [b]问题补充:[/b] [code="java"] UserBusinessImpl 如果不是通过spring get的 后面的照样无法注入成功 听我的试一下 我过去带的人就有这么错的 估计你的问题也是这个[/code] 没有明白你所说的spring get的 按我的理解就是,在action层,也使用同样的set注入.如果是这样的话,我有尝试过,但是是失败的,也是空指针,只不是报在action层了,也就是注入失败. [b]问题补充:[/b] [quote] 的确是没有获得到dao 你获得UserBusinessImpl 的方式应该不对吧 你是如何获得UserBusinessImpl 的? 那句代码贴出来看看 [/quote] UserBusiness business = new UserBusinessImpl(); 我是直接new的,我也尝试过像service层那样注入,一样没效果 [code="java"] 看你配置看不出有什么问题,有可能是DAO方法里某行报错了。 [/code] 应该还没到dao层,dao层的LOG都没打出来,应该就属于注入失败. [b]问题补充:[/b] [quote] 你new ClassPathXmlApplicationContext()的这个过程就是对配置文件的解析 以及按着你所配置的方式通过反射机制自动给你进行装配 如果没有这个过程 你直接new那就相当于在堆内存上开辟一个空的对象 里面没有任何的东西 所以你取出的dao是空 因为你没往里放东西啊,而UserBusinessImpl userBusinessImpl = (UserManager)factory.getBean("UserBusinessImpl ");是从已经放着解析并且装配好的所有对象的大容器里去取 所以你取出来的是装配好的啊 [/quote] 我把UserBusinessImpl改了下就可以了, [code="java"] public Person getUserFromEXTNO(String extNo) throws Exception { BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDAL userDal = (UserDAL)factory.getBean("userDao"); return userDal.getUserFromEXTNO(extNo); } [/code] 但是为什么使用set注入不行 [b]问题补充:[/b] 非常谢谢各位的解答 现在的结果是,我在action,service层使用getBean都可以获取到实例,但是使用set注入都是失败的. [code="java"] <bean name="/userLoginAction" class="com.ccsee.happytrip.web.action.UserLoginAction"> <property name="userBusiness" ref="userBusiness"></property> </bean> <bean id="userBusiness" class="com.ccsee.happytrip.service.impl.UserBusinessImpl"> <property name="userDAL" ref="userDao"></property> </bean> <bean id="userDao" class="com.ccsee.happytrip.dao.impl.UserDALImpl"> </bean> [/code] action层 [code="java"] private UserBusiness userBusiness; public void setUserBusiness(UserBusiness userBusiness) { this.userBusiness = userBusiness; } Person user = userBusiness.getUserFromEXTNO(form.getUserName() .trim()); [/code] 如果使用getBean就行,有朋友说必须都使用spring拖管就行了,我现在 action和service的都放在spring托管中,dao没办法托管必须用原来的. 我想问下原因,谢谢. [b]问题补充:[/b] 我的struts有加载spring strust-config.xml [code="java"] <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml" /> </plug-in> [/code]
springboot抽象类中注入实例,使用@Autowired注解托管实例,注入实例为空获取不到值的问题。
https://blog.csdn.net/loney_wolf/article/details/103505788 以上博客对springboot抽象类无法注入实例化做了解决,虽然解决了抽象类注入实体为空的情况,但是不知具体解决原理是什么。 </br> </br> </br> 抽象类不能实例化,因此在抽象类中不能注入其他实例,因为无法被spring托管。然而对抽象类的子类进行实例化托管之后,抽象类中进行注入托管的实例却能正正常注入,这是为什么(个人定位是java多态的向上向下转型)
Spring-data-redis的RedisTemplate @Autowared注入为空
## 最近在学习Spring整合redis,配置了一个项目启动时报错,请各位大神看一下,谢谢啦: --- 20-Mar-2017 15:33:12.293 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log No Spring WebApplicationInitializer types detected on classpath 20-Mar-2017 15:33:12.324 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext 20-Mar-2017 15:33:18.281 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisUserDAO' defined in file [/home/ob/Projects/im-system/im-server/build/libs/exploded/im-service-1.0.0.war/WEB-INF/classes/com/xxx/im/dao/redis/RedisUserDAO.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.xxx.im.dao.redis.RedisUserDAO]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1116) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1060) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4717) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734) at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1702) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300) at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819) at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801) at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:456) at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:405) ... Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.xxx.im.dao.redis.RedisUserDAO]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1108) ... 58 more Caused by: java.lang.NullPointerException at com.xxx.im.dao.redis.RedisBaseDAO.getKeySerializer(RedisBaseDAO.java:28) at com.xxx.im.dao.redis.RedisUserDAO.<init>(RedisUserDAO.java:20) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ... 60 more --- ## spring配置: 1. spring-config.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!-- applicationContext --> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <aop:aspectj-autoproxy/> <!-- 配置文件注入 --> <context:property-placeholder location="classpath:config.properties"/> <context:component-scan base-package="com.xxx.im"/> <bean class="com.xxx.im.util.SpringUtils"/> <import resource="classpath:spring-config-*.xml"/> </beans> ``` 2. spring-config-redis ``` <?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="${jedis.maxTotal}"/> <property name="maxIdle" value="${jedis.maxIdle}"/> <property name="minIdle" value="${jedis.minIdle}"/> <property name="maxWaitMillis" value="${jedis.maxWaitMillis}"/> <property name="minEvictableIdleTimeMillis" value="${jedis.minEvictableIdleTimeMillis}"/> <property name="numTestsPerEvictionRun" value="${jedis.numTestsPerEvictionRun}"/> <property name="timeBetweenEvictionRunsMillis" value="${jedis.timeBetweenEvictionRunsMillis}"/> <property name="testOnBorrow" value="${jedis.testOnBorrow}"/> <property name="testOnReturn" value="${jedis.testOnReturn}"/> <property name="testWhileIdle" value="${jedis.testWhileIdle}"/> </bean> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> <property name="hostName" value="${redis.hostname}"/> <property name="port" value="${redis.port}"/> <property name="timeout" value="${redis.timeout}"/> <property name="database" value="${redis.database}"/> <property name="password" value="${redis.password}"/> <property name="usePool" value="${redis.userPool}"/> <property name="poolConfig" ref="jedisPoolConfig"/> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="connectionFactory"/> <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" p:connection-factory-ref="connectionFactory"/> </beans> ``` 3. 调用出错代码 ``` package com.mzj.im.dao.redis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; import javax.annotation.Resource; /** * Created by xx on 17-3-17. */ public abstract class RedisBaseDAO <K, V> { @Autowired protected RedisTemplate<K, V> redisTemplate; public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) { this.redisTemplate = redisTemplate; } protected RedisSerializer<K> getKeySerializer(){ return (RedisSerializer<K>) redisTemplate.getKeySerializer(); } protected RedisSerializer<V> getValueSerializer(){ return (RedisSerializer<V>) redisTemplate.getValueSerializer(); } } ``` 4. 断点调试 ![图片说明](https://img-ask.csdn.net/upload/201703/20/1489997260_384518.png)
Spring注入action的Service为什么总是为空啊?
<p>话不多说,上代码:</p> <p>类Person,接口PersonDAO,接口PersonService略</p> <p>实现类PersonDAOImpl:</p> <pre name="code" class="java">package web.dao.impl; import java.util.List; import org.hibernate.LockMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import web.dao.PersonDAO; import web.entity.Person; /** * A data access object (DAO) providing persistence and search support for * Person entities. Transaction control of the save(), update() and delete() * operations can directly support Spring container-managed transactions or they * can be augmented to handle user-managed Spring transactions. Each of these * methods provides additional information for how to configure it for the * desired type of transaction control. * * @see web.entity.Person * @author MyEclipse Persistence Tools */ public class PersonDAOImpl extends HibernateDaoSupport implements PersonDAO { private static final Logger log = LoggerFactory.getLogger(PersonDAOImpl.class); // property constants public static final String PASSWORD = "password"; protected void initDao() { // do nothing } public void save(Person transientInstance) { log.debug("saving Person instance"); try { getHibernateTemplate().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(Person persistentInstance) { log.debug("deleting Person instance"); try { getHibernateTemplate().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Person findById(java.lang.String id) { log.debug("getting Person instance with id: " + id); try { Person instance = (Person) getHibernateTemplate().get( "web.entity.Person", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(Person instance) { log.debug("finding Person instance by example"); try { List results = getHibernateTemplate().findByExample(instance); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding Person instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Person as model where model." + propertyName + "= ?"; return getHibernateTemplate().find(queryString, value); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByPassword(Object password) { return findByProperty(PASSWORD, password); } public List findAll() { log.debug("finding all Person instances"); try { String queryString = "from Person"; return getHibernateTemplate().find(queryString); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public Person merge(Person detachedInstance) { log.debug("merging Person instance"); try { Person result = (Person) getHibernateTemplate().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Person instance) { log.debug("attaching dirty Person instance"); try { getHibernateTemplate().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Person instance) { log.debug("attaching clean Person instance"); try { getHibernateTemplate().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } }</pre> <p> </p> <p>这是myeclipse自己生成的也应该没有啥问题。</p> <p>PersonServiceImpl:</p> <pre name="code" class="java">package web.service.impl; import web.dao.PersonDAO; import web.entity.Person; import web.service.PersonService; public class PersonServiceImpl implements PersonService { private PersonDAO personDAO; public boolean equals(Object obj) { return personDAO.equals(obj); } public PersonDAO getPersonDAO() { return personDAO; } public void setPersonDAO(PersonDAO personDAO) { this.personDAO = personDAO; } public int hashCode() { return personDAO.hashCode(); } public String toString() { return personDAO.toString(); } @Override public void doSave(Person person) { personDAO.save(person); } } </pre> <p> </p> <p>PersonAction:</p> <pre name="code" class="java">package web.action; import web.entity.Person; import web.service.PersonService; import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial") public class PersonAction extends ActionSupport { private String username; private String password; 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; } private PersonService personService; public PersonService getPersonService() { return personService; } public void setPersonService(PersonService personService) { this.personService = personService; } public String doSave() { Person person = new Person(); person.setUsername(username); person.setPassword(password); System.out.println(PersonDAO);/////////////////////////////////////////////////////////////这里是NULL NULL NULL 调了一天 要疯了 personService.doSave(person); return SUCCESS; } } </pre> <p> </p> <p>applicationContext.xml:</p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 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-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt; &lt;property name="driverClassName"&gt; &lt;value&gt;com.mysql.jdbc.Driver&lt;/value&gt; &lt;/property&gt; &lt;property name="url"&gt; &lt;value&gt;jdbc:mysql://localhost:3306/test&lt;/value&gt; &lt;/property&gt; &lt;property name="username"&gt; &lt;value&gt;root&lt;/value&gt; &lt;/property&gt; &lt;property name="password"&gt; &lt;value&gt;1234&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt; &lt;!-- &lt;property name="configLocation" value="classpath:hibernate.cfg.xml"&gt; &lt;/property&gt; --&gt; &lt;property name="dataSource" ref="dataSource"/&gt; &lt;property name="mappingResources"&gt; &lt;list&gt; &lt;value&gt;web/dao/hibmap/Person.hbm.xml&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLInnoDBDialect&lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.che.provider_class"&gt;org.hibernate.che.HashtableCheProvider&lt;/prop&gt; &lt;prop key="hibernate.query.ftory_class"&gt;org.hibernate.hql.classic.ClassicQueryTranslatorFtory&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;tx:advice id="txAdvice" transaction-manager="txManager"&gt; &lt;tx:attributes&gt; &lt;tx:method name="get*" read-only="true" propagation="SUPPORTS" /&gt; &lt;tx:method name="find*" read-only="true" propagation="SUPPORTS" /&gt; &lt;tx:method name="*" read-only="false" propagation="REQUIRED" /&gt; &lt;/tx:attributes&gt; &lt;/tx:advice&gt; &lt;aop:config&gt; &lt;aop:pointcut id="txDAO" expression="execution (* dao.*.*(..))" /&gt; &lt;aop:advisor pointcut-ref="txDAO" advice-ref="txAdvice" /&gt; &lt;/aop:config&gt; &lt;!-- DAOs --&gt; &lt;bean id="PersonDAOImpl" class="web.dao.impl.PersonDAOImpl" scope="singleton"&gt; &lt;property name="sessionFactory" ref="sessionFactory"/&gt; &lt;/bean&gt; &lt;!-- Services --&gt; &lt;bean id="PersonServiceImpl" class="web.service.impl.PersonServiceImpl" scope="prototype"&gt; &lt;property name="personDAO" ref="PersonDAOImpl"/&gt; &lt;/bean&gt; &lt;!-- Actions --&gt; &lt;bean name="PersonAction" class="web.action.PersonAction" scope="prototype"&gt; &lt;property name="personService" ref="PersonServiceImpl"/&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <p> </p> <p>web.xml:</p> <pre name="code" class="java">&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/classes/applicationContext.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;filter&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;filter-class&gt;org.apache.struts2.dispatcher.FilterDispatcher&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;url-pattern&gt;*.action&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app&gt;</pre> <p>  struts.xml:</p> <pre name="code" class="java">&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"&gt; &lt;struts&gt; &lt;constant name="struts.objectFactory" value="spring"&gt;&lt;/constant&gt; &lt;package name="default" namespace="/" extends="struts-default"&gt; &lt;action name="PersonAction" class="web.action.PersonAction" method="doSave"&gt; &lt;result name="success"&gt;/success.jsp&lt;/result&gt; &lt;/action&gt; &lt;/package&gt; &lt;/struts&gt; </pre> <p> </p> <p>这是错误:</p> <p> </p> <pre>java.lang.NullPointerException web.action.PersonAction.doSave(PersonAction.java:42) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) 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:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 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:237) 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:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 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:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395) </pre> <p>我不明白我的spring配置文件没有找到什么映射错误,而且action中,service中都有注入类的set方法,可是为什么是null值,高手请指教,不胜感激!</p>
dwr 调用spring bean 但是在bean中的其他注入bean为空
dwr 调用spring bean 但是在bean中的其他注入bean为空 请各位大哥指点下 public class UsersService{ private BaseServiceDao dao; public BaseServiceDao getDao() { return dao; } public void setDao(BaseServiceDao dao) { this.dao = dao; } public String ajaxService(){ System.out.println(dao) return ""; } } 在js中调用ajaxService 输出的dao为空是为什么,如果在jsp中用以下方式调用是正常的 WebApplicationContext cont = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext()); UsersService usersService=(UsersService)cont.getBean("usersService"); usersService.ajaxService();
Spring注入对象为null,是什么原因造成
我打算在TestAction对象里面注入A360Action对象,两个bean都已经配置好了,但是注入A360Action对象的时候提示空指针对象异常,在debug模式下发现注入的A360Action对象为null,检查了一下代码,配置文件没有问题,bean的setter,getter方法也都有,奇怪的是其他的bean也是按一样的方法配置,可以正常注入,到底是哪里出了问题,此时没有什么头绪,望大神指点一二。。。。。拜谢。。。 ``` <bean id="testAction" class="com.demo.web.action.TestAction"> <property name="wandoujiaAction" ref="wandoujiaAction" /> ........ <property name="a360Action" ref="a360Action" /> <property name="vodafoneAction" ref="vodafoneAction" /> </bean> ``` 下面是A360Action的配置 ``` <bean id="a360Action" class="com.demo.web.action.A360Action"> <property name="baseHiveFactoryDao" ref="baseHiveFactoryDao" /> </bean> ``` 下面是baseHiveFactoryDao的配置信息 ``` <bean id="baseHiveFactoryDao" class="com.gsta.hive.dao.BaseHiveFactoryDao"> </bean> ```
Spring自动注入的对象为null
在配置文件中,配置了TableService类,所有其他自动注入的地方都有值,但是我起了一个udp的监听,在解析protobuf类中,自动注入的TableService对象为空
Service为什么为什么注入为空
1.首先我的Dao层注入成功,已经测试成功,但是Controller成注入Service时,发现注入的Service为空。 2.配置文件 ## 2.1 web.xml ## ..... ## <context-param> ## <param-name>contextConfigLocation</param-name> ## <param-value>classpath:application-context.xml</param-value> ## </context-param> ## <!-- spring的监听器 --> ## <listener> ## <listener-class>org.springframework.web.context.ContextLoaderListener</li stener-class> ## </listener> ## ...... ## 2.2 application-context.xml ## <import resource="config/*.xml"/> ## ## 2.3 config文件下xml配置文件 ## ****anotation.xml ## <!--spring 扫包 @Service .....--> ## <context:component-scan base-package="cn.itcast"> ## <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> ## </context:component-scan> ## ## <context:annotation-config/> 其余配置文件为Dao层数据库相关,以及sql映射文件的配置,就不写了 # 2.4 Springmvc的配置文件 # <!-- springmvc扫包 --> # <context:component-scan base-package="cn.itcast" use-default-filters="false"> # <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> # </context:component-scan> # <!-- 配置全局日期转换器 --> # <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> # <property name="webBindingInitializer"> # <bean class="cn.itcast.core.web.DateConversion"></bean> # </property> # # </bean> # <!-- jsp视图解析器 --> # <bean name="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> # <property name="prefix" value="/WEB-INF/back_page/"></property> # <property name="suffix" value=".jsp"></property> # </bean> 测试类 @Autowired BrandDao brandDao; BrandService brandService; @Test public void test3() throws Exception{ Brand brand = new Brand(); brand.setIsDisplay(1); //当前页码(如果当前页码小于1或者为空时,将其置为1) brand.setPageNo(1); System.out.println(brandService); Pagination pagination=brandService.getBrandListWithPage(brand); } } Service实现类 @Service @Transactional public class BrandServiceImpl { @Autowired BrandDao brandDao; @Transactional(readOnly = true) public Pagination getBrandListWithPage(Brand brand) { /* * @pageNo:当前页码 * * @pageSize:每页的记录数 * * @totalCount:总记录数 */ System.out.println(brandDao); System.out.println(brandDao.getBrandCount(brand)); int pageNo=brand.getPageNo(); Pagination pagination=new Pagination(Pagination.cpn(pageNo), 5, brandDao.getBrandCount(brand)); pagination.setList(brandDao.getBrandListWithPage(brand)); return pagination; } }
spring注解注入的对象为空
<p>本人想测试一下spring注解的用法,但是刚开始就遇到了问题。就是注入的对象为null.</p> <p> </p> <p>首先,加入了spring的jars。如下:</p> <p>1、common-annotations.jar</p> <p>2、commons-dbcp.jar</p> <p>3、commons-io.jar</p> <p>4、commons-logging.jar</p> <p>5、commons-pool.jar</p> <p>6、spring.jar</p> <p> </p> <p>然后,在web.xml中加入了配置信息。如下:</p> <p>&lt;!-- 配置文件位置 --&gt;</p> <p>&lt;context-param&gt;<br>    &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;<br>     &lt;param-value&gt;/WEB-INF/classes/applicationContext.xml&lt;/param-value&gt;<br> &lt;/context-param&gt;<br> <br> &lt;!-- spring的监听器 --&gt;<br> &lt;listener&gt;<br>        &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;<br> &lt;/listener&gt;</p> <p> </p> <p>然后,写了两个测试类。如下:</p> <p>package demo;</p> <p> </p> <p>public class Users {</p> <p> private String name;<br> private int age;</p> <p> public String getName() {<br>  return name;<br> }</p> <p> public void setName(String name) {<br>  this.name = name;<br> }</p> <p> public int getAge() {<br>  return age;<br> }</p> <p> public void setAge(int age) {<br>  this.age = age;<br> }<br>}</p> <p>--------------------------------</p> <p>package demo;</p> <p>import javax.annotation.Resource;</p> <p> </p> <p>public class Info {</p> <p> private Users user;</p> <p> </p> <p> public Users getUser() {<br>  return user;<br> }</p> <p> </p> <p> @Resource(name="users")<br> public void setUser(Users user) {<br>  this.user = user;<br> }<br>}</p> <p> </p> <p>然后,在applicationContext.xml中配置bean。如下:</p> <p>     &lt;context:annotation-config/&gt;<br>     <br>     &lt;bean id="users" class="demo.Users"&gt;&lt;/bean&gt;</p> <p> </p> <p>然后,在index.jsp中输入Info.User。如下:</p> <p>&lt;%<br>  Info info = new Info();<br> %&gt;<br> &lt;%=info.getUser() %&gt;</p> <p> </p> <p>然后,输入的结果为 null.</p> <p> </p> <p>请问高手,这是什么原因?谢谢</p>
spring注入对象为null的问题
本人使用ssh2做一个接口,用两种方式实现,一种是从web页面上手动导入,一种用到了quartz技术,定时触发。写好了应用之后,第一种是没有问题,用第二种的时候每次作业调度业务逻辑层的时候,都提示注入的dao对象为空,折腾了两天也找不到原因在那里?请各位帮忙看看问题所在下面贴下关键代码。 service层是定义了一个接口,一个实现类,代码如下:[code="java"]public class QueryLYUserTableServiceImpl implements QueryLYUserTableService { QueryLYUserTableDao dao1; InsertPowerUserTableDao dao2; public List<InsertTable> queryInsertTable() { // TODO Auto-generated method stub return dao1.queryInsertTable(); } public QueryLYUserTableDao getDao1() { return dao1; } public void setDao1(QueryLYUserTableDao dao1) { this.dao1 = dao1; } public InsertPowerUserTableDao getDao2() { return dao2; } public void setDao2(InsertPowerUserTableDao dao2) { this.dao2 = dao2; } }[/code] applicationContext.xml如下:[code="java"]<bean id="dao1" class="com.ly.dbInterface.orm.dao.QueryLYUserTableDaoImpl" autowire="byName"> <property name="sessionFactory"> <ref bean="sessionFactory1" /> </property> </bean> <bean id="dao2" class="com.ly.dbInterface.orm.dao.InsertPowerUserTableDaoImpl" autowire="byName"> <property name="sessionFactory"> <ref bean="sessionFactory2" /> </property> </bean> <bean id="service" class="com.ly.dbInterface.manager.service.QueryLYUserTableServiceImpl" autowire="byName"> <property name="dao1"> <ref local="dao1" /> </property> <property name="dao2"> <ref local="dao2" /> </property> </bean> <bean id="courseService" class="com.ly.dbInterface.taskscheduler.service.CourseService"/> <bean name="reportJbo" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="courseService" /> <property name="targetMethod" value="start"/> </bean> <bean name="simpleTriggerBean" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <!--这里定义定时任务的对象的位置--> <property name="jobDetail" ref="reportJbo"/> <!--这里定义每六秒钟程序执行一次--> <property name="repeatInterval" value="1200000"/> <!--这里定义程序启动两秒钟后开始执行--> <property name="startDelay" value="30000"/> </bean> <!-- 启动任务 --> <bean name="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="simpleTriggerBean"/> </list> </property> </bean>[/code] 请各位看看
Spring+hibernate注入空异常
http://blog.csdn.net/nixingfujiuhao/article/details/17069115 http://blog.csdn.net/nixingfujiuhao/article/details/17069217
Spring mvc在controller注入service报空
今天配置spring mvc时一直报空,找不到问题在哪里。希望各位帮帮忙。 tomcat能正常启动,没有报错,但是在调用controller时注入的service对象为null web.xml配置 <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>rest</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> applicationContext.xml已有: <context:component-scan base-package="com"/> <mvc:default-servlet-handler/> <mvc:annotation-driven /> controller代码 @Controller @RequestMapping(value = "/sync") public class servicecontroller extends BaseController{ @javax.annotation.Resource(name = "syncClientService") private ISyncClientService syncClientService; @RequestMapping(value = "/start") @ResponseBody private String syncStart(HttpServletRequest request) throws Exception{ CreLogger.info("**********Strat invoke synchusers..."); JSONObject jsonPara = getJsonPara(request); String sychUrl = jsonPara.getString("syncurl"); SynchroniseuserResponse response = syncClientService.syncUserStart(sychUrl); if (response != null) { SynchroniseuserResponseType responseType = response.getSynchroniseuserResponse(); if (responseType.getResultCode() == 0) { CreLogger.info("**********同步成功..."); return "同步成功!"; }else { CreLogger.info("**********同步失败..."); return "同步失败!"; } }else { CreLogger.info("**********同步失败..."); return "同步失败!"; } } } service代码: @Service("syncClientService") public class syncClientService implements ISyncClientService{ private static com.dayangit.cre.util.CreLogger CreLogger = com.dayangit.cre.util.CreLogger.getLogger(servicecontroller.class); @javax.annotation.Resource(name = "AuthorizationManager") private AuthorizationManager authorizationManager; @SuppressWarnings("null") public SynchroniseuserResponse syncUserStart(String url) { try { SynchroniseUsersServiceStub stub = new SynchroniseUsersServiceStub(url); SynchroniseuserRequest request = new SynchroniseuserRequest(); SynchroniseuserRequestType requestType = new SynchroniseuserRequestType(); //设置全局同步 CreLogger.info("**********设置全局同步**********"); requestType.setSyncAll(true); ModifiedModuleInfoType moduleInfo = new ModifiedModuleInfoType(); requestType.setModifiedModuleInfo(moduleInfo); request.setSynchroniseuserRequest(requestType); SynchroniseuserResponse response = stub.synchroniseUsers(request); return response; } catch (Exception e) { CreLogger.error("exception",e); } return null; } 里面的具体逻辑就省了,很长
爬虫福利二 之 妹子图网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.两种思维方式在求职面试中,经常会考察这种问题:北京有多少量特斯拉汽车? 某胡同口的煎饼摊一年能卖出多少个煎饼? 深圳有多少个产品经理? 一辆公交车里能装下多少个乒乓球? 一
相关热词 c# 输入ip c# 乱码 报表 c#选择结构应用基本算法 c# 收到udp包后回包 c#oracle 头文件 c# 序列化对象 自定义 c# tcp 心跳 c# ice连接服务端 c# md5 解密 c# 文字导航控件
立即提问