利用注解注入service,会空指针异常。而用getBean方式则可以获取到service

在整合springmvc和mybatis时,在controller中注入service,无法注入,具体代码如下

@Controller
public class ItemsController {
@Autowired
private ItemsService itemsService;

@RequestMapping("/queryItems")
public ModelAndView queryItems(){
    if (itemsService == null)
        System.out.println("DDDDDDDDDDDDDDDDDD");
    List<ItemsCustom> itemsList = itemsService.findItemsList(null);
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("itemsList", itemsList);
    modelAndView.setViewName("items/itemsList");
    return modelAndView;
}

}

public interface ItemsService {
public List findItemsList(ItemsQueryVo itemsQueryVo);
}

public class ItemsServiceImpl implements ItemsService {
@Autowired
private ItemsMapperCustom itemsMapperCustom;

@Override
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo){
    return itemsMapperCustom.findItemsList(itemsQueryVo);
}

}

spring的配置,已经在这里非注解的配置了service的bean
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- DAO部分 -->

<context:property-placeholder location="classpath:db.properties" />

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="maxActive" value="30" />
    <property name="maxIdle" value="5" />
</bean>


<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="ssm.mapper"></property>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>




<!-- service部分 -->

<bean id="itemsService" class="ssm.service.impl.ItemsServiceImpl" />

<!-- <context:component-scan base-package="ssm.service.impl"></context:component-scan> 
    <context:annotation-config /> -->

<!-- 事务部分 -->

<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="save*" propagation="REQUIRED" />
        <tx:method name="insert*" propagation="REQUIRED" />
        <tx:method name="delete*" propagation="REQUIRED" />
        <tx:method name="update*" propagation="REQUIRED" />
        <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
        <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
    </tx:attributes>
</tx:advice>

<aop:config>
    <aop:advisor advice-ref="txAdvice"
        pointcut="execution(* ssm.service.impl.*.*(..))" />
</aop:config>

2个回答

试试@resource应该就好了

qq_36798995
qq_36798995 试过了,@Resource(name="itemsService"),这个结果还是一样
3 年多之前 回复

在ItemsServiceImpl 文件加一个@Service的注解

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
service利用注解注入,会空指针异常。而用getBean方式则可以获取到service。

**spring配置文件如下:** <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="placeholderProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:conf/config.properties</value> </list> </property> <property name="fileEncoding" value="utf-8" /> </bean> <import resource="spring-hibernate.xml" /> <!-- Import basic SpringMVC Resteasy integration --> <import resource="classpath:springmvc-resteasy.xml" /> <!-- 扫描文件 --> <context:component-scan base-package="com.sinopec.carlife" /> </beans> **service接口如下:** package com.sinopec.carlife.service.api; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.sinopec.carlife.model.Region; @Path("/regions") @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) public interface RegionService { /** * 获取所有城市 * @return * @throws Exception */ @POST @Path("/all") public List<Region> findRegions() throws Exception; } **service实现类如下:** package com.sinopec.carlife.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sinopec.carlife.dao.RegionDAO; import com.sinopec.carlife.model.Region; import com.sinopec.carlife.service.api.RegionService; @Service("regionService") public class RegionServiceImpl implements RegionService { @Autowired private RegionDAO regionDAO; @Override public List<Region> findRegions() throws Exception { return regionDAO.findRegions(); } } **junit测试如下:** package test.com.sinopec.carlife; import java.util.List; import javax.annotation.Resource; import junit.framework.TestCase; import org.junit.Test; import com.sinopec.carlife.model.Region; import com.sinopec.carlife.service.api.RegionService; public class RegionServiceTest extends TestCase { @Resource(name="regionService") private RegionService regionService; @Test public void testFindRegions() { try { /*ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring.xml"); regionService = (RegionService) context.getBean("regionService");*/ List<Region> regions = regionService.findRegions(); System.out.println(regions.size()); } catch (Exception e) { e.printStackTrace(); } } }

Spring注入Bean出现空指针异常

``` @Bean public ServletRegistrationBean ActionServlet() { ServletRegistrationBean registration = new ServletRegistrationBean(); registration.setName("ActionServlet"); registration.setOrder(1); registration.addUrlMappings("*.do"); registration.setServlet(new ActionServlet()); registration.addInitParameter("config", "/WEB-INF/conf/action_config.xml"); registration.addInitParameter("ignoreCase", "N"); registration.setLoadOnStartup(1); return registration; } ``` ``` java.lang.NullPointerException: null at org.dom4j.io.SAXReader.read(SAXReader.java:284) at com.yuangou.ecp.bp.web.controller.ActionMappingsParse.parse(ActionMappingsParse.java:34) at com.yuangou.ecp.bp.web.controller.servlet.ActionServlet.init(ActionServlet.java:502) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1144) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:986) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4978) at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedContext.deferredLoadOnStartup(TomcatEmbeddedContext.java:78) at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.performDeferredLoadOnStartup(TomcatEmbeddedServletContainer.java:288) at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.start(TomcatEmbeddedServletContainer.java:211) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:297) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:145) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:134) at com.murong.ecp.bp.common.util.ECPApplication.run(ECPApplication.java:30) at com.murong.ecp.netpay.jnefss.web.SpringBootApplication.main(SpringBootApplication.java:18) ```

spring框架用注解的方式装配属性为什么老是空指针异常

UserDao的实现类UserDaoImp package com.two; import org.springframework.stereotype.Repository; @Repository("userDao") public class UserDaoImp implements UserDao { @Override public void say() { // TODO Auto-generated method stub System.out.println("dao say hello spring"); } } UserService 的实现类UserServiceImp package com.two; import javax.annotation.Resource; import org.springframework.stereotype.Service; @Service ("userService") public class UserServiceImp implements UserService { @Resource(name="userDao") public UserDao userDao; public void say() { this.userDao.say(); // TODO Auto-generated method stub System.out.println("service say hello spring"); } } bean.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <bean id="userDao" class="com.two.UserDaoImp"/> <bean id="userService" class="com.two.UserServiceImp"/> </beans> 测试类Test package com.two; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { String xmlPath="com/two/bean.xml"; // TODO Auto-generated method stub ApplicationContext applicationcontext= new ClassPathXmlApplicationContext(xmlPath); UserServiceImp userdao=(UserServiceImp) applicationcontext.getBean("userService"); userdao.say(); } } 错误提示 Exception in thread "main" java.lang.NullPointerException at com.two.UserServiceImp.say(UserServiceImp.java:13) at com.two.Test.main(Test.java:14)

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一直报空

spring setter注入时报空指针错误的问题,希望高手路过看一下

报错信息 [code="java"] java.lang.NullPointerException at com.dareway.apps.demo.test.TestController.save(TestController.java:52) 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.dareway.apps.common.webcontroller.MultiActionController.invokeNamedMethod(MultiActionController.java:456) at com.dareway.apps.common.webcontroller.MultiActionController.handleRequestInternal(MultiActionController.java:375) at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153) at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:857) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:792) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:475) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:440) at javax.servlet.http.HttpServlet.service(HttpServlet.java:709) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at com.dareway.apps.common.webcontroller.SafetyFilter.doFilter(SafetyFilter.java:114) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at com.dareway.apps.common.webcontroller.EncodingFilter.doFilter(EncodingFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520) at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929) at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705) at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683) at java.lang.Thread.run(Thread.java:595) [/code] web.xml中的配置 [code="java"] .... <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> .... [/code] applicationContext.xml中的配置: [code="java"] .... <!-- 测试接口的配置 --> <bean id="testDemo" class="com.dareway.apps.demo.test.TestDemo"> </bean> <bean id="TestController" class="com.dareway.apps.demo.test.TestController"> <property name="testDemo"> <ref bean="testDemo" /> </property> </bean> .... [/code] TestDemo.java的内容: [code="java"] public class TestDemo implements TestInterface { public void printDemo() { System.out.print("测试成功"); } } [/code] TestInterface 的内容: [code="java"] public interface TestInterface { public void printDemo(); } [/code] testController中的内容: [code="java"] public class TestController extends BizDispatchControler { private TestInterface testDemo; public ModelAndView save(HttpServletRequest request, HttpServletResponse response, TestDTO dto) throws Exception { ... // WebApplicationContext applicationContext = WebApplicationContextUtils // .getWebApplicationContext(request.getSession().getServletContext()); // TestDemo testDemo=(TestDemo) applicationContext.getBean("testDemo");//这样我就可以 // 得到非空的testdemo。但是这不是setter注入吧? testDemo.printDemo();//报空指针的地方 ... return null; } public void setTestDemo(TestInterface testDemo) { this.testDemo = testDemo; } } [/code] 不知道这样配置到底是那个地方出了问题? [b]问题补充:[/b] [code="java"] package com.dareway.apps.demo.test; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.servlet.ModelAndView; import com.dareway.apps.common.ClassHelper; import com.dareway.apps.common.exception.ApplicationException; import com.dareway.apps.common.log.BizLogHandler; import com.dareway.apps.common.pub.util.DataObject; import com.dareway.apps.common.pub.util.DataStore; import com.dareway.apps.common.webcontroller.BizDispatchControler; import com.dareway.apps.common.webcontroller.Delegator; public class TestController extends BizDispatchControler { private TestInterface testDemo; public ModelAndView enterTest(HttpServletRequest request, HttpServletResponse response, TestDTO dto) throws Exception { return new ModelAndView("test"); } public ModelAndView query(HttpServletRequest request, HttpServletResponse response, TestDTO dto) throws Exception { DataObject pdo = new DataObject(); DataStore vds = null; try { pdo.put("dto", dto); Delegator dele = new Delegator(); DataObject result = dele.execute( "com.dareway.apps.demo.test.TestBPO", "query", pdo, getUser(request));// 用自己的bpo以及方法。 vds = (DataStore) result.get("vds"); } catch (ApplicationException e) { BizLogHandler.saveBizLog(request, e.getMessage()); return this.showErrorMessage(e.getMessage()); } return this.flashDataWindow(request, vds); } public ModelAndView save(HttpServletRequest request, HttpServletResponse response, TestDTO dto) throws Exception { DataObject pdo = new DataObject(); // WebApplicationContext applicationContext = WebApplicationContextUtils // .getWebApplicationContext(request.getSession().getServletContext()); //TestDemo testDemo=(TestDemo) applicationContext.getBean("testDemo"); testDemo.printDemo(); // try { Collection entities = ClassHelper.getEntities(request,TestDTO.class,"testdatawindow3"); pdo.put("dto", dto); pdo.put("entities", entities); Delegator dele = new Delegator(); return alertSuccessMessage("保存补贴成功。"); } // public TestInterface getTestDemo() { // return testDemo; // } // public void setTestDemo(TestInterface testDemo) { this.testDemo = testDemo; } } [/code] 这是测试程序的源程序,我做了删改,所以行数可能不对。 我的问题是为什么注入不了。 报的问题就是testDemo=null [b]问题补充:[/b] [code="java"] <bean id="testDemo" class="com.dareway.apps.demo.test.TestDemo"> </bean> <bean id="TestController" class="com.dareway.apps.demo.test.TestController"> <property name="testDemo"> <ref bean="testDemo" /> </property> </bean> [/code] 这个是正确的,如果不正确的 在tomcat启动的应该就报错吧? 楼下的让我改成 <bean id="testDemo" class="com.dareway.apps.demo.test.TestInterface"> TestInterface是个接口 这样不对吧? [b]问题补充:[/b] 你的controller不是由spring创建的。。。 它继承的是MultiActionController 这样不行吗?

使用getbean是ioc注入吗

如题,使用applicationContext对象的getbean方法获得了对象 这是依赖注入吗? 我只知道,在容器里定义的对象可以互相注入,这是依赖注入。 而main方法使用getbean来获得对象 这算是注入到main方法里吗? 举个例子,有A、B、C三个类 B依赖C 在容器里定义了C类的bean,又定义了B类的bean B的属性里需要C的对象,在容器里将C的bean注入进去 。 A不在容器里,A有main方法使用getbean方法获得B的对象。 从A获得B的对象的方式来看,算是注入吗

Spring 定时任务 在执行方法时报空指针

定时任务的xml: <bean id="autoIPV6BusinessAlarmStatisticsJob" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass"> <value>com.boco.auto.AutoIPV6BusinessAlarmStatisticsReport</value> </property> </bean> <bean id="autoIPV6BusinessAlarmStatistics" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail"> <ref local="autoIPV6BusinessAlarmStatisticsJob" /> </property> <property name="cronExpression"> <value>0 30 3 * * ?</value> </property> </bean> Spring注入: <bean name="/ReportCommonActionPipeRes" class="com.boco.web.struts.action.report.ReportCommonActionPipeRes" parent="baseAction"> <property name="reportCommonDao"> <ref local="reportCommonDao" /> </property> <property name="reportCommonDao_Local"> <ref local="reportCommonDao_Local" /> </property> <property name="reportCommonGroupDao"> <ref local="reportCommonGroupDao" /> </property> <property name="reportCommonService"> <ref local="reportCommonService" /> </property> <property name="linkReportDao_Local"> <ref local="linkReportDao_Local" /> </property> <property name="mysqlBaseDao"> <ref bean="mysqlBaseService" /> </property> <property name="statementManagementBean"> <ref bean="statementManagementBean" /> </property> <!-- add liuhuipeng --> <property name="vendorfaultService"> <ref local="vendorfaultService" /> </property> </bean> <bean id="vendorfaultService" class="com.boco.alarm.service.impl.VendorFaultReportServiceImpl"> <property name="reportCommonDao"> <ref local="reportCommonDao"/> </property> <property name="reportCommonDao_Local"> <ref local="reportCommonDao_Local" /> </property> <property name="alarmReportDao"> <ref local="alarmReportDao" /> </property> <property name="statementManagementBean"> <ref bean="statementManagementBean" /> </property> </bean> 定时任务: public class AutoAlarmStatisticsReport implements Job{ static Logger logger = Logger.getLogger(AutoAlarmStatisticsReport.class) ; private ReportCommonActionPipeRes pipeResAction; @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { logger.info("+++进入定时任务。+++"); generateReport(); } public void generateReport(){ logger.info("modelName=AlarmStatistics"); pipeResAction = (ReportCommonActionPipeRes)StartupApp.getInstance(). getAppContext().getBean("reportpiperesource"); String modelName = "IPV6BusinessAlarmStatistics"; Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String today = sdf.format(date); this.pipeResAction.insertBusinessNEStatistics(modelName); //insertBusinessNEStatistics(modelName); } } 调用此方法: public boolean insertBusinessNEStatistics(String modelName){ boolean isOk = false; Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String createDate = sdf.format(date); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date datestart = new Date(); String startDateString=""; startDateString= sdf1.format(datestart); List<Map> Allist = new ArrayList(); String informixSql = statementManagementBean.getStatementByName(modelName.trim()); Map parameterMap = new HashMap(); if((null == informixSql)||informixSql.equalsIgnoreCase("no such table")){ return isOk; }else{ String[] sql_Array = informixSql.split(";"); List<Map> dataList = new ArrayList<Map>(); for(String sql : sql_Array){ if(sql != null && sql.trim().length() > 0){ if(modelName.equalsIgnoreCase("AlarmStatistics")){ String procName = "{call pro_alarm_trans_counteveryday()}"; boolean isInsertflag= false; //测试: isInsertflag = true; // try { // isInsertflag = vendorfaultService.insertIPV6AlarmCount(procName); // logger.info("++获得告警标识:++"+isInsertflag); // } catch (Exception e) { // TODO: handle exception // logger.error("error 错误的信息", e); // } if(isInsertflag == true){ try{ dataList = vendorfaultService.queyAlarm(parameterMap, sql.trim(), false); }catch(Throwable t){ logger.error("error 错误的信息", t); } }else{ return isInsertflag; } }else{ //dataList = reportCommonDao.commonQuery(sql.trim(), parameterMap); dataList = reportCommonDao.commonQuery(sql.trim(), parameterMap); } } } isOk = true; } return isOk; }

Spring aop 为什么注解方式获取的并无法进入?Autowired getBean

请问下我配置的AOP写日志 为什么private static ApprovalService approvalService = SpringContextHolder.getBean("approvalService"); 这样获取bean就可以进入切面, @Autowired private ApprovalService approvalService; 用注解就不行呢?

Spring注入失败,但是getBean();却可以使用

<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd "> <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:jboss/PostgresDS"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="packagesToScan" value="com.cn.Jpa"> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <!-- 依赖注入上面定义的sessionFactory --> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <!-- 依赖注入上面定义的事务管理器transactionManager --> <property name="transactionManager" ref="transactionManager" /> <!-- 定义需要进行事务拦截的方法及所采用的事务控制类型 --> <property name="transactionAttributes"> <props> <!-- 以browse、list、load、get及is开头的所有方法采用只读型事务控制类型 --> <prop key="browse*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="list*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="is*">PROPAGATION_REQUIRED,readOnly</prop> <!-- 所有方法均进行事务控制,如果当前没有事务,则新建一个事务 --> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <!-- 定义BeanNameAutoProxyCreatorf进行Spring的事务处理 --> <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <!-- 针对指定的bean自动生成业务代理 --> <property name="beanNames"> <list> <value>HibernateManDao</value> <value>LoginResource</value> </list> </property> <!-- 这个属性为true时,表示被代理的是目标类本身而不是目标类的接口 --> <property name="proxyTargetClass"> <value>true</value> </property> <!-- 依赖注入上面定义的事务拦截器transactionInterceptor --> <property name="interceptorNames"> <list> <value>transactionInterceptor</value> </list> </property> </bean> <bean id="dao" class="com.cn.persistent.HibernateManDao"> <!-- <constructor-arg index="0" ref="sessionFactory" /> --> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> <property name="session"><null/></property> </bean> <bean id="servlet" class="com.cn.servlet.LoginResource" scope="prototype"> <property name="md"> <ref bean="dao"/> </property> <!-- <constructor-arg index="0" ref= "dao"/> --> </bean> </beans>

timer定时器在项目初始化的时候注入service为null

定时器任务开始执行的时候,一直没办法加载,后来发现是service为null 这是定时器执行的方法,在调用TimeWorkAction以后,里面的service就是null了 ``` public class WorkTimer extends HttpServlet{ //时间间隔(一天) private static final long PERIOD_DAY = 24 * 60 * 60 * 1000; @Override public void init() throws ServletException { // TODO Auto-generated method stub System.out.println("开始执行定时器查询"); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 19); //夜晚23点 calendar.set(Calendar.MINUTE, 57); calendar.set(Calendar.SECOND, 0); Date date=calendar.getTime(); //第一次执行定时任务的时间 TimerTask task = new TimeWorkAction(); Timer timer = new Timer(); timer.schedule(task,date, PERIOD_DAY); super.init(); } } ``` ``` @Component public class TimeWorkAction extends TimerTask{ WorkService workService = (WorkService)ApplicationContextUtil.getBean("workService"); Work work = (Work)ApplicationContextUtil.getBean("work"); public void run(){ try { //获取当前日期 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = new Date(); String dates = simpleDateFormat.format(date1); long currentDate = 0; try { currentDate = simpleDateFormat.parse(dates).getTime(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } //获取权限用户 List userName = workService.getName(); for (int i = 0; i < userName.size(); i++) { Object obj = userName.get(i); String name = obj.toString(); List addDate = workService.addDate(name,currentDate); if(addDate.isEmpty()){ work = new Work(); work.setName(name); work.setWorkDate(currentDate); workService.save(work); } } } catch (Exception e) { e.printStackTrace(); } } public WorkService getWorkService() { return workService; } public void setWorkService(WorkService workService) { this.workService = workService; } public Work getWork() { return work; } public void setWork(Work work) { this.work = work; } } ``` 之前service直接private WorkService workService也不行

如何用属性注入的方式为spring的service注入Mybatis的Mapper对象?

万能的网友的。帮帮我吧。 spring+Mybatis+struts2整合中遇到一个问题:service层中不知道如何注入Mapper对象啊。 首先我分三层。action---> service---->Mapper(充当dao层)。 我的Mapper是扫描包生成实现类的。然而我的service里面有一个Mapper对象。 就像这样: public class ProductService { //@Autowired private ProductMapper productMapper; public void setProductMapper(ProductMapper productMapper) { this.productMapper = productMapper; } //省略其他代码。。。 } 然后我想通过setter方法将productMapper注入到ProductService中。 我的配置文件如下: <bean id="Mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name="basePackage" value="wm.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <bean id="productService" class="wm.service.ProductService" scope="prototype" > <property name="productMapper" ref=""></property> </bean> 写到这里,我忽然愣住了。这是我不知道ref该怎么写。或者还是value怎么写。如果用注解注入的话,我能解决这个问题。但是如果我用属性注入的方式怎么实现呢?大神们,没有分。不好意思啊。

java关于hibernate和spring整合,在action层无法注入,报空指针错误。

以下为spring配置部分代码 ``` <bean id="testAction" class="com.sven.action.TestAction"> <property name="memberService"> <ref bean="memberService"/> </property> </bean> <bean id="memberService" class="com.sven.service.impl.SwMemberServiceImpl"> <property name="memberDao"> <ref bean="memberDao"/> </property> </bean> <bean id="memberDao" class="com.sven.dao.impl.SwMemberDaoImpl"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> ``` 目录结构如下: ![目录结构](https://img-ask.csdn.net/upload/201708/09/1502281879_661840.png) 经过测试service和dao层注入没有问题。 在action类中,出现错误,代码如下: ``` package com.sven.action; import org.junit.Test; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import com.sven.entity.SwMember; import com.sven.service.SwMemberService; public class TestAction{ /** * 注入业务层 */ private SwMemberService memberService; public void setMemberService(SwMemberService memberService) { this.memberService = memberService; } @Test public void testAction() { SwMember member = this.memberService.findMemberById(19); System.out.println(member.getUsername() + " "+member.getName()); } // @Test public void test() { XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml")); SwMemberService dao = (SwMemberService) factory.getBean("memberService"); SwMember member = dao.findMemberById(19); System.out.println(member.getUsername() + " "+member.getName()); } } ``` 运行test方法可以成功,获取到数据; 运行testAction方法报错:报错如下: ![报错](https://img-ask.csdn.net/upload/201708/09/1502282015_361210.png) 小白一枚,望大神指点!

SSM中Controller自动注入service失败

Root Cause org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'loginServiceImpl'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ssm.service.LoginServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:364) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1269) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:171) javax.servlet.GenericServlet.init(GenericServlet.java:158) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:745) ## 在Controller中自动注入service就报以上错误 ![图片说明](https://img-ask.csdn.net/upload/202004/13/1586763996_66970.jpg) ## 该service为 ![图片说明](https://img-ask.csdn.net/upload/202004/13/1586764249_143874.jpg) spring-dao.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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"> <!--读取properties文件 --> <context:property-placeholder location="classpath:db.properties" /> <context:annotation-config></context:annotation-config> <!--配置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>${driver}</value> </property> <property name="url"> <value>${url}</value> </property> <property name="username"> <value>${username}</value> </property> <property name="password"> <value>${password}</value> </property> </bean> <!-- 配置sqlsessionFactory --> <!-- 查看源码便可知注入的property的名字 --> <!-- 可以读取mybatis-config.xml文件,也可以不读取,信息全都在配置在spring中 --> <!-- <property name="configLocation" value="classpath:mybatis-config.xml" /> --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.ssm.bean"></property> <property name="configurationProperties"> <props> <prop key="cacheEnabled">true</prop> <prop key="lazyLoadingEnabled">false</prop> </props> </property> <!--告诉spring扫描映射文件 --> <property name="mapperLocations" value="classpath:com/ssm/dao/mapper/*.xml"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ssm.dao.mapperInterface"></property> </bean> </beans> ``` ## 以下是spring-service.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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.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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描添加了spring注解的类 --> <context:component-scan base-package="com.ssm.service.*" /> <!-- 采用注解方式配置 --> <context:annotation-config /> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置事务拦截器 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- 注入事务属性 --> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="select*" propagation="REQUIRED" rollback-for="Exception" /> </tx:attributes> </tx:advice> <!-- spring的aop配置 --> <aop:config proxy-target-class="true"> <aop:pointcut id="txPointcut" expression="execution(* com.ssm.service..*.*(..)) " /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config> </beans> ``` ## 以下spring-web.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:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 配置SpringMVC --> <!-- 1.开启SpringMVC注解模式 --> <!-- 简化配置: (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持 --> <mvc:annotation-driven /> <!-- 采用注解方式配置 --> <context:annotation-config /> <!-- 2.静态资源默认servlet配置 (1)加入对静态资源的处理:js,gif,png (2)允许使用"/"做整体映射 --> <!-- <mvc:resources mapping="/images/**" location="/images/"/> <mvc:resources mapping="/js/**" location="/js/"/> <mvc:resources mapping="/css/**" location="/css/"/> <mvc:resources mapping="/fonts/**" location="/fonts/"/> <mvc:resources mapping="/script/**" location="/script/"/> --> <mvc:default-servlet-handler/> <!-- 3.配置jsp 显示ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/page/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 4.扫描web相关的bean --> <context:component-scan base-package="com.ssm.web.controller" /> </beans> ``` ##最后是web.xml ``` <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>SSMDemo</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> <!-- 配置spring读取的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-dao.xml classpath:spring-service.xml </param-value> </context-param> <!--配置监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 如果是用mvn命令生成的xml,需要修改servlet版本为3.1 --> <!-- 配置DispatcherServlet --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置springMVC需要加载的配置文件 spring-dao.xml,spring-service.xml,spring-web.xml Mybatis - > spring -> springmvc --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-web.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 默认匹配所有的请求 --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置编码过滤 --> <filter> <filter-name>CharacterEncodingFilter</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/</url-pattern> </filter-mapping> </web-app> ``` ##求解决!!

使用Spring在Service中注入了Dao的对象,在Service中怎么获取Dao的对象

使用Spring在Service中注入了Dao的对象,然后在Service中需要使用Dao对象的话,可以用ApplicationContext的getBean方法,我这边看的一个程序没有用ApplicationContext,而是在Service中对Dao对象进行了声明,然后定义了Dao对象的set和get方法,这样也可以吗,还是说这个程序我没有看明白,希望有明白的可以给解释一下,另希望有大神可以带带,或者有正在学java的一块做个伴,多交流交流

spring注入service时报错。求解

SEVERE: Context initialization failed org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productAction': Unsatisfied dependency expressed through field 'productService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.duobao.modules.service.inter.ProductService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) 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:761) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5229) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5516) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649) at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1763) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301) at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819) at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:792) at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:618) at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:565) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301) at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819) at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:792) at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1486) at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:96) at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1327) at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1419) at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:847) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322) at sun.rmi.transport.Transport$1.run(Transport.java:177) at sun.rmi.transport.Transport$1.run(Transport.java:174) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.transport.Transport.serviceCall(Transport.java:173) at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:722) Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.duobao.modules.service.inter.ProductService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ... 65 more spring配置: <context:component-scan base-package="com.duobao.modules"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> </context:component-scan> springMVC配置: <context:component-scan base-package="com.duobao.modules.web"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>

注解注入的bean和从上下文取出的bean不是同一个?

有以下代码,最后比较注入的dao和ApplicationContext 上下文取出的dao,不是同一个。是我哪里有错误吗? public class SpringApplicationContext implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext context) throws BeansException { applicationContext = context; } public static Object getBean(String name) { return applicationContext.getBean(name); } public static ApplicationContext getApplicationContext(){ return applicationContext; } } ``` @Repository(value="helloDao") public class HelloDao { public void save(){ System.out.println("HelloDao.save"); } } ``` @Service("helloService") public class HelloService { @Resource(name = "helloDao") private HelloDao dao; public void say() { System.out.println(SpringApplicationContext.getBean("helloDao")==dao);//false System.out.println("say hello"); } }

ssh整合getHibernateTemplate().find()报空指针异常

[color=darkred][/color] 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.microsoft.sqlserver.jdbc.SQLServerDriver"> </property> <property name="url" value="jdbc:microsoft:sqlserver://localhost:1433;databasename=zf"> </property> <property name="username" value="sa"></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 </prop> <prop key="hibernate.show_sql"> true </prop> </props> </property> <property name="mappingResources"> <list> <value>com/chen/model/TblFwlx.hbm.xml</value> <value>com/chen/model/TblFwxx.hbm.xml</value> <value>com/chen/model/TblJd.hbm.xml</value> <value>com/chen/model/TblQx.hbm.xml</value> <value>com/chen/model/TblUser.hbm.xml</value></list> </property></bean> <bean name="FwxxDao" class="com.cao.dao.FwxxDao"/> <bean name="LoginDao" class="com.cao.dao.LoginDao"/> </beans> applicationcontext-aop.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: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" default-autowire="byName" default-lazy-init="true"> <!-- 以AspectJ方式 定义 AOP --> <aop:config proxy-target-class="true"> <aop:advisor pointcut="execution(* com.cao.dao.*Dao.*(..))" advice-ref="txAdvice" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" propagation="REQUIRED" read-only="true"/> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="*" propagation="REQUIRED" read-only="true"/> </tx:attributes> </tx:advice> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans> FwxxAction代码: public class FwxxAction extends DispatchAction { private FwxxDao fwxxDao; public FwxxDao getFwxxDao() { return fwxxDao; } public void setFwxxDao(FwxxDao fwxxDao) { this.fwxxDao = fwxxDao; } @Override protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return doList(mapping, form, request, response); } public ActionForward doList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("in..........doList"); System.out.println("fwxxDao======="+fwxxDao); int index=1; int pageSize=5; try{ String str=request.getParameter("index"); index=Integer.parseInt(str); }catch(Exception e){ } List list=fwxxDao.getAll(); request.setAttribute("list", list); return mapping.findForward("fwxxList"); } } Dao代码: package com.cao.dao; import java.util.List; import com.cao.model.tblFwxx; public class FwxxDao extends BaseDao<tblFwxx> { public FwxxDao() { super.cls=tblFwxx.class; } public List getFwxx(){ return super.getAll(); } } BaseDao代码: public class BaseDao<T> extends HibernateDaoSupport { protected Class cls; public List<T> getAll(){ return getHibernateTemplate().findByExample(cls); } } struts-config.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <data-sources /> <form-beans > <form-bean name="fwxxForm" type="com.cao.struts.form.FwxxForm" /> </form-beans> <global-exceptions /> <global-forwards ></global-forwards> <action-mappings > <action attribute="fwxxForm" name="fwxxForm" parameter="method" path="/fwxx" scope="request" type="com.cao.struts.action.FwxxAction" > <forward name="fwxxList" path="/WEB-INF/jsp/FwxxList.jsp"></forward> </action> </action-mappings> <controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/> <message-resources parameter="com.chen.struts.ApplicationResources" /> <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"/> </struts-config> action-servlet.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" default-autowire="byName"> <bean name="/fwxx" class="com.cao.struts.action.FwxxAction"/> </beans> web.xml代码: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-*.xml</param-value> </context-param> <!-- 著名 Character Encoding filter --> <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> <!--Hibernate Open Session in View Filter控制Session的连接--> <filter> <filter-name>hibernateFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <filter-mapping> <filter-name>hibernateFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>3</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>3</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> 最后运行,getHibernateTemplate()为空,调用它的find方法抛空指针异常 用ApplicationContext con=new ClassPathXmlApplicationContext("applicationContext-*.xml"); con.getBean("FwxxDao"); 可以得到对象并可以调它的方法

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; } }

可以获取到从页面传过来的参数,为什么报空指针呢?

我通过打桩,可以从页面获取到参数,但是在调用方法往方法里面传参的时候,报空指针异常。 ``` if (id != null && id.length > 0) { ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); IPurchase purchase = (IPurchase) context.getBean("purchaseProxy"); purchase.setSId(session.getAttribute("userId").toString()); //这里是可以获取到参数的 System.out.println(id); purchase.insertById(id); ``` ``` public boolean insertById(String[] id) { boolean result=false; ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); IDataConfig myData = (IDataConfig) context.getBean("dataConfigProxy"); myData.init(); try { myData.openConnection(); myData.beginTransaction(); for(int i=0;i<id.length;i++){ myData.addBatch("delete from purchase where id ="+id[i]); } if(myData.commit()){ result=true; }else{ result=false; } myData.endTransaction(); } catch (SQLException e) { e.printStackTrace(); }finally{ myData.closeConnection(); } return result; ``` ``` java.lang.NullPointerException at com.sun.proxy.$Proxy5.insertById(Unknown Source) at com.genius.sales_Manage.purchase.action.InsertHCAction.handleRequest(InsertHCAction.java:63) at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.genius.util.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:56) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) ```

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

springboot+jwt实现token登陆权限认证

一 前言 此篇文章的内容也是学习不久,终于到周末有时间码一篇文章分享知识追寻者的粉丝们,学完本篇文章,读者将对token类的登陆认证流程有个全面的了解,可以动态搭建自己的登陆认证过程;对小项目而已是个轻量级的认证机制,符合开发需求;更多精彩原创内容关注公主号知识追寻者,读者的肯定,就是对作者的创作的最大支持; 二 jwt实现登陆认证流程 用户使用账号和面发出post请求 服务器接受到请求后使用私...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

早上躺尸,晚上干活:硅谷科技公司这么流行迟到?

硅谷科技公司上班时间OPEN早已不是什么新鲜事,早九晚五是常态,但有很多企业由于不打卡,员工们10点、11点才“姗姗来迟”的情况也屡见不鲜。 这种灵活的考勤制度为人羡慕,甚至近年来,国内某些互联网企业也纷纷效仿。不过,硅谷普遍弹性的上班制度是怎么由来的呢?这种“流行性迟到”真的有那么轻松、悠哉吗? 《动态规划专题班》 课程试听内容: 动态规划的解题要领 动态规划三大类 求最值/计数/可行性 常...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大胆预测下未来5年的Web开发

在2019年的ReactiveConf 上,《Elm in Action》的作者Richard Feldman对未来5年Web开发的发展做了预测,很有意思,分享给大家。如果你有机会从头...

立即提问
相关内容推荐