SpringUtils工具类
package com.gjw.go.common.utils
import org.springframework.beans.factory.config.BeanFactoryPostProcessor
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.stereotype.Component
@Component
class SpringUtils : BeanFactoryPostProcessor, ApplicationContextAware {
override fun postProcessBeanFactory(beanFactory: ConfigurableListableBeanFactory) {
SpringUtils.beanFactory = beanFactory
}
override fun setApplicationContext(applicationContext: ApplicationContext) {
SpringUtils.applicationContext = applicationContext
}
companion object {
private lateinit var beanFactory: ConfigurableListableBeanFactory
private lateinit var applicationContext: ApplicationContext
fun <T> getBean(name: String): T {
return applicationContext.getBean(name) as T
}
fun <T> getBean(requiredType: Class<T>): T? {
return applicationContext.getBean(requiredType)
}
fun <T> getBean(name: String, requiredType: Class<T>): T? {
return applicationContext.getBean(name, requiredType)
}
fun <T> getBeansOfType(requiredType: Class<T>): Map<String, T> {
return applicationContext.getBeansOfType(requiredType)
}
}
}
单元测试
AbstractSpringTest
package com.test.service
import com.gjw.go.GoApp
import com.gjw.go.common.log.log
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
@RunWith(SpringRunner::class)
@SpringBootTest(classes = [GoApp::class], webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
abstract class AbstractSpringTest {
@BeforeTest
fun beforeTest(){
log.info("BeforeTest 进行资源初始化操作")
}
@AfterTest
fun afterTest(){
log.info("AfterTest 进行资源释放操作")
}
}
SpringUtilsTest
package com.test.service
import com.gjw.go.common.utils.SpringUtils
import com.gjw.go.service.EasyExcelService
import kotlin.test.Test
class SpringUtilsTest : AbstractSpringTest() {
@Test
fun test() {
SpringUtils.getBean<EasyExcelService>("easyExcelServiceImpl").listAll()
Thread.sleep(1000)
SpringUtils.getBean<EasyExcelService>("myExcelServiceImp").listAll()
Thread.sleep(1000)
}
@Test
fun test33() {
SpringUtils.getBean("easyExcelServiceImpl", EasyExcelService::class.java)?.listAll()
Thread.sleep(1000)
SpringUtils.getBean("myExcelServiceImp", EasyExcelService::class.java)?.listAll()
Thread.sleep(1000)
}
@Test
fun test3ee3() {
var list = SpringUtils.getBeansOfType(EasyExcelService::class.java)
list.values.forEach {
it.listAll()
println("---------")
}
}
}