Tag Archives: spring

[Solved] In case of “transactionmanager” while setting bean property “transactionmanager” error

When learning to write XML transactions in spring, you can refer to ‘transactionmanager’ while setting bean property ‘transactionmanager’

Warning: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in file [D:\Codeworkstation\IDEAGuigu\Spring5\spring5_tedemo1\out\production\spring5_tedemo1\com\atgui\spring\service\UserService.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'txadvice': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' available

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in file [D:\Codeworkstation\IDEAGuigu\Spring5\spring5_tedemo1\out\production\spring5_tedemo1\com\atgui\spring\service\UserService.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'txadvice': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' available

XML configuration transaction code

 <!-- Create the transaction manager - >
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<! -- Inject data source -- >
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <! -2 Configuration Notifications-->
    <tx:advice id="txadvice">
        <! -- Configure transaction parameters -->
        <tx:attributes>
            <! -- Specify which rule's method to add a transaction on top of -->
            <tx:method name="account" propagation="REQUIRED"/>
            <! --<tx:method name="account*"/>-->
        </tx:attributes>
    </tx:advice>

    <! -3 Configuring entry points and cut-planes -->
    <aop:config>
        <! -- Configure entry points -->
        <aop:pointcut id="pt" expression="execution(* com.atgui.spring.service.UserService.*(...))" />
        <! --configuration cutscene ->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
    </aop:config>

Service layer code

@Service
//@Transactional
public class UserService {

    @Autowired
    private UserDao userDao;

    public void account(){

        //Reduce money
        userDao.reducemo();
        int i=13/0;
        //Increase money
        userDao.addmo();
    }
}

The above error appears when running

You can modify the error code section in XML

 <!-- Creating a Transaction Manager-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--        Injecting data sources-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

Change the above id = “datasourcetransactionmanager” to id = “transactionmanager”\

That’s it

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--        Injecting data sources-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
``

This will solve the above problem


Frequent log swiping after Nacos client starts [How to Solve]

# 1, according to the heartbeat log, locate the package name of the log output
c.a.n.client.config.impl.ClientWorker : get changedGroupKeys:[]

# 2. Search the package path where ClientWorker is located in IDEA  
package com.alibaba.nacos.client.config.impl;

# 3. Set the package path logging to ERROR or WARN in any configuration file format
# Nacos registry client heartbeat logging is disabled get changedGroupKeys:[] 
logging:
  level:
    com.alibaba.nacos.client.config.impl: WARN
  
# 4. If it is Spring Cloud Gateway then you need to configure it as logging:
  level:
    com.alibaba.nacos.client.*: WARN    

[Solved] javax.servlet.ServletException: Servlet[springmvc] Servlet.init()

1. There are many cases of this exception. First of all,
when configuring sqlsessionfactorybean, you should not pay attention to the problem (see the figure)

the same as above, when configuring other places, you also use ref as value. For example,

PS: combined with the above, it can discharge itself. Pay attention to whether it is this problem

2. Problems that we didn’t pay attention to when configuring servlets with web.xml

as shown in the figure: after the integration, the configuration file should not be MVC, but should be all. Generally, when creating a configuration file, there will be a prompt in the upper right corner, which may cause this kind of problem if you don’t pay attention to it. Generally, my solution is to use the import tag (as shown in the figure)

import all the configuration files into a general file
and then import the web and XML into the general file as follows

PS: there are some special reasons, which vary from person to person. Hope someone can add!

[Solved] SpringBoot Error: This application has no explicit mapping for /error, so you are seeing this

Springboot project running error:

If you check the directory, the problem lies in the URL in the controller
(1) if: @ requestmapping (“/”)

the URL should be written:

(2) if the URL is like this:

Then @ requestmapping (“/ users”)

is a very simple question… As a result, I took a long walk to look at the XML file and properties for half a day… To record this little problem

[Solved] Flowable Start Error: ClassCastException: java.time.LocalDateTime cannot be cast to java.lang.String

Springboot2 + MySQL integrated flowable6.6.0, failed to start

In liquibase.changelog.standardchangeloghistoryservice, there is such a code:

Object tmpDateExecuted = rs.get("DATEEXECUTED");
    Date dateExecuted = null;
    if (tmpDateExecuted instanceof Date) {
        dateExecuted = (Date)tmpDateExecuted;
    } else {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            dateExecuted = df.parse((String)tmpDateExecuted);
        } catch (ParseException var24) {
    }
}

The dateexecuted field in the database is of timestamp type. When the version of the database driver package used is relatively new (8.0.23 is used here), the returned type is localdatetime. If it is strongly converted to string, an error will be reported

Modify the driver package version to 8.0.19, and the service starts normally

Nacos failed to start [How to Solve]

Nacos failed to start

    1. Modify config/application.properties to configure the corresponding database information
#*************** Config Module Related Configurations ***************#
### If use MySQL as datasource:
spring.datasource.platform=mysql

### Count of DB:
db.num=1

### Connect URL of DB:
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user=root
db.password=123456
      1. create the corresponding database Nacos, and execute the corresponding config/nacos-mysql.sql single node startup.cmd – M standalone, modify the default single node startup, and modify bin/startup.cmd. Line 26 is as follows
rem set MODE="cluster"
set MODE="standalone"

[Solved] Java.lang.ClassCastException: [Ljava.lang.Long; cannot be cast to java.util.List

preface

Recently, I used the Renren fast framework to transform a crawler 3.0 project, and found an official bug java. Lang. ClassCastException: [ljava. Lang. long; Can't be cast to Java. Util. List , because long [] can't be converted to List & lt; Object caused.
Detailed error report

2021-06-20 22:14:48.436 ERROR 15920 --- [io-8080-exec-18] i.r.common.exception.RRExceptionHandler  : nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: java.lang.ClassCastException: class [Ljava.lang.Long; cannot be cast to class java.util.List ([Ljava.lang.Long; and java.util.List are in module java.base of loader 'bootstrap')
### The error may exist in file [D:\workspace\spring\TenderFetchSystem\tfs-admin\target\classes\mapper\job\ScheduleJobDao.xml]
### The error may involve io.renren.modules.job.dao.ScheduleJobDao.updateBatch
### The error occurred while executing an update
### Cause: java.lang.ClassCastException: class [Ljava.lang.Long; cannot be cast to class java.util.List ([Ljava.lang.Long; and java.util.List are in module java.base of loader 'bootstrap')

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: java.lang.ClassCastException: class [Ljava.lang.Long; cannot be cast to class java.util.List ([Ljava.lang.Long; and java.util.List are in module java.base of loader 'bootstrap')
### The error may exist in file [D:\workspace\spring\TenderFetchSystem\tfs-admin\target\classes\mapper\job\ScheduleJobDao.xml]
### The error may involve io.renren.modules.job.dao.ScheduleJobDao.updateBatch
### The error occurred while executing an update
### Cause: java.lang.ClassCastException: class [Ljava.lang.Long; cannot be cast to class java.util.List ([Ljava.lang.Long; and java.util.List are in module java.base of loader 'bootstrap')
	at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:92)
	at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:440)
	at com.sun.proxy.$Proxy90.update(Unknown Source)
	at org.mybatis.spring.SqlSessionTemplate.update(SqlSessionTemplate.java:287)
	at com.baomidou.mybatisplus.core.override.MybatisMapperMethod.execute(MybatisMapperMethod.java:65)
	at com.baomidou.mybatisplus.core.override.MybatisMapperProxy.invoke(MybatisMapperProxy.java:96)
	at com.sun.proxy.$Proxy152.updateBatch(Unknown Source)
	at io.renren.modules.job.service.impl.ScheduleJobServiceImpl.updateBatch(ScheduleJobServiceImpl.java:100)
	at io.renren.modules.job.service.impl.ScheduleJobServiceImpl.pause(ScheduleJobServiceImpl.java:118)
	at io.renren.modules.job.service.impl.ScheduleJobServiceImpl$$FastClassBySpringCGLIB$$1.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
	at io.renren.modules.job.service.impl.ScheduleJobServiceImpl$$EnhancerBySpringCGLIB$$1.pause(<generated>)
	at io.renren.modules.job.controller.ScheduleJobController.pause(ScheduleJobController.java:115)
	at io.renren.modules.job.controller.ScheduleJobController$$FastClassBySpringCGLIB$$1.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
	at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:88)
	at io.renren.common.aspect.SysLogAspect.around(SysLogAspect.java:52)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644)
	at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633)
	at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
	at org.apache.shiro.spring.security.interceptor.AopAllianceAnnotationsAuthorizingMethodInterceptor$1.proceed(AopAllianceAnnotationsAuthorizingMethodInterceptor.java:82)
	at org.apache.shiro.authz.aop.AuthorizingMethodInterceptor.invoke(AuthorizingMethodInterceptor.java:39)
	at org.apache.shiro.spring.security.interceptor.AopAllianceAnnotationsAuthorizingMethodInterceptor.invoke(AopAllianceAnnotationsAuthorizingMethodInterceptor.java:115)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
	at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
	at io.renren.modules.job.controller.ScheduleJobController$$EnhancerBySpringCGLIB$$1.pause(<generated>)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:112)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at io.renren.common.xss.XssFilter.doFilter(XssFilter.java:30)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61)
	at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
	at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
	at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
	at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
	at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
	at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
	at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
	at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
	at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:387)
	at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
	at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
	at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
	at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
	at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:96)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:41002)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.base/java.lang.Thread.run(Thread.java:834)

Solutions

1. First of all, of course, it starts with interface call

through debugging, it is found that Vue calls the back-end “/ pause” interface

2. Do it by yourself. Through a simple analysis of the code, to locate the problem
originally, it was map.put ("list", jobids) but jobids is not List , the problem is ~
by using arrays.aslist (jobids) to directly convert the object to List type, the problem is solved!

@Service("scheduleJobService")
public class ScheduleJobServiceImpl extends ServiceImpl<ScheduleJobDao, ScheduleJobEntity> implements ScheduleJobService {
//Selected from ScheduleJobServiceImpl This class, omitting other irrelevant content.

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void pause(Long[] jobIds) {
        // Iterate and stop the job
		for(Long jobId : jobIds){
    		ScheduleUtils.pauseJob(scheduler, jobId);
    	}
        //Update the status after stopping the job
    	updateBatch(jobIds, Constant.ScheduleStatus.PAUSE.getValue());
    }
	@Override
    public int updateBatch(Long[] jobIds, int status){
    	Map<String, Object> map = new HashMap<>(2);
    	//fix official bug,by zhengkai.blog.csdn.net
    	map.put("list", Arrays.asList(jobIds));
    	map.put("status", status);
    	return baseMapper.updateBatch(map);
    }

}
    

3. Verification

Jsonformat annotation solves the problem of time format in the front end of localdatetime

Annotation @ jsonformat is mainly the conversion of time format from background to foreground

Annotation @ dataformat is mainly the conversion of time format from front to back to background

@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date symstarttime;
 
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date symendtime;

Automatic configuration of springboot and application.yml

We need to know that when springboot starts, it will be automatically configured, find meta-inf/spring. Factors , and load it into the IOC container

enter the file and find any class
click in<

see the @ enableconfigurationproperties ({serverproperties. Class}) annotation
click in serverproperties. Class

this means that the class is bound to the application.yml file
in which the value of prefix represents the

in the YML file All kinds of properties of this class are those of this class

the above is spring boot auto configuration and application. YML contact!!!

The @ Autowired annotation in springboot is invalid in ordinary classes. How to solve and use the null pointer exception java.lang.nullpointerexception

Code directly

1. To create a serviceutils tool class, annotate it with @ Autowired

package com.deao.app.socket.netty.server.service.impl;

import com.deao.app.socket.netty.server.service.MessageService;
import com.deao.app.socket.netty.server.service.SocketGasExamArrangeManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class ServiceUtils {
    @Autowired
    public SocketGasExamArrangeManageService socketGasExamArrangeManageService;
    @Autowired
    public MessageService messageService;
    public static ServiceUtils serviceUtils;

    @PostConstruct
    public void init() {
        serviceUtils = this;
    }

}

Used elsewhere

    public static void main(String[] args) {
        serviceUtils.socketGasExamArrangeManageService.selectGasExamArrangeManageByStudentId(studentId);
        serviceUtils.messageService.message(null, request, account, null, true);
    }

 

Failed to retrieve platformtransactionmanager for @ transactional test: [defaulttest]

Foreword: This is JUnit test class. I hope that the data can be rolled back after the test, and the previous data will not be affected. But I have no problem in other tutorials. I report an error, and then I check a lot of data, but it is fruitless. Finally, I solve it by myself

Error message: java.lang.illegalstateexception: failed to retrieve platformtransactionmanager for @ transactional test

java.lang.IllegalStateException: Failed to retrieve PlatformTransactionManager for @Transactional test: [DefaultTestContext@6356695f testClass = SystemServiceTest, testInstance = com.****.****.oc.coresystem.service.SystemServiceTest@716f94c1, testMethod = update@SystemServiceTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4f18837a testClass = SystemServiceTest, locations = '{}', classes = '{class com.****.****.Application, class com.****.****.Application}', contextInitializerClasses = '[]', activeProfiles = '{dev}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@4d3167f4, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@87f383f, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@5891e32e, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@42607a4f], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> false]]
	at org.springframework.util.Assert.state(Assert.java:94) ~[spring-core-5.1.18.RELEASE.jar:5.1.18.RELEASE]
	at org.springframework.test.context.transaction.TransactionalTestExecutionListener.beforeTestMethod(TransactionalTestExecutionListener.java:185) ~[spring-test-5.1.18.RELEASE.jar:5.1.18.RELEASE]
	at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:291) ~[spring-test-5.1.18.RELEASE.jar:5.1.18.RELEASE]
	at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) [spring-test-5.1.18.RELEASE.jar:5.1.18.RELEASE]
	at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) [spring-test-5.1.18.RELEASE.jar:5.1.18.RELEASE]
	at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) [spring-test-5.1.18.RELEASE.jar:5.1.18.RELEASE]
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) [junit-4.12.jar:4.12]
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251) [spring-test-5.1.18.RELEASE.jar:5.1.18.RELEASE]
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.1.18.RELEASE.jar:5.1.18.RELEASE]
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-5.1.18.RELEASE.jar:5.1.18.RELEASE]
	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.1.18.RELEASE.jar:5.1.18.RELEASE]
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) [spring-test-5.1.18.RELEASE.jar:5.1.18.RELEASE]
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69) [junit-rt.jar:na]
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33) [junit-rt.jar:na]
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220) [junit-rt.jar:na]
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53) [junit-rt.jar:na]

The core reason for this problem in my project is that I have three different data sources in this large project, and JUnit does not know which data source transaction you want to roll back! It requires you to specify a platform transaction manager

Configuration of one of the primary data sources:

The test class then specifies the transactionmanager

Re run the test method, the problem is solved!

 
 

spring boot-beans in application context form a cycle

  Spring’s bean generation cycle conflicts, as shown in the following figure:

To exclude some configurations

@SpringBootApplication(exclude = {RedisAutoConfiguration.class,DataSourceAutoConfiguration.class, XADataSourceAutoConfiguration.class,
         JdbcTemplateAutoConfiguration.class})