這篇文章主要為大家展示了Springboot如何實(shí)現(xiàn)自動裝配,內(nèi)容簡而易懂,希望大家可以學(xué)習(xí)一下,學(xué)習(xí)完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
成都創(chuàng)新互聯(lián)長期為1000多家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為南縣企業(yè)提供專業(yè)的成都網(wǎng)站建設(shè)、成都網(wǎng)站制作,南縣網(wǎng)站改版等技術(shù)服務(wù)。擁有10余年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。
創(chuàng)建一個簡單的項(xiàng)目:
<?xml version="1.0" encoding="UTF-8"?>4.0.0 spring-boot-starter-parent org.springframework.boot 2.1.12.RELEASE com.xiazhi demo 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test
首先創(chuàng)建自定義注解:
package com.xiazhi.demo.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * MyComponent 作用于類上,表示這是一個組件,于component,service注解作用相同 * @author zhaoshuai */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface MyComponent { }
package com.xiazhi.demo.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 作用于字段上,自動裝配的注解,與autowired注解作用相同 * @author zhaoshuai */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Reference { }
然后寫配置類:
package com.xiazhi.demo.config; import com.xiazhi.demo.annotation.MyComponent; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.filter.AnnotationTypeFilter; /** * @author ZhaoShuai * @company lihfinance.com * @date Create in 2020/3/21 **/ public class ComponentAutoConfiguration implements ImportBeanDefinitionRegistrar, ResourceLoaderAware { private ResourceLoader resourceLoader; @Override public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) { String className = annotationMetadata.getClassName(); String basePackages = className.substring(0, className.lastIndexOf(".")); ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(beanDefinitionRegistry, false); scanner.addIncludeFilter(new AnnotationTypeFilter(MyComponent.class)); scanner.scan(basePackages); scanner.setResourceLoader(resourceLoader); } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } }
上面是配置掃描指定包下被MyComponent注解標(biāo)注的類并注冊為spring的bean,bean注冊成功后,下面就是屬性的注入了
package com.xiazhi.demo.config; import com.xiazhi.demo.annotation.MyComponent; import com.xiazhi.demo.annotation.Reference; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; /** * @author ZhaoShuai * @company lihfinance.com * @date Create in 2020/3/21 **/ @SpringBootConfiguration public class Configuration implements ApplicationContextAware { private ApplicationContext applicationContext; @Bean public BeanPostProcessor beanPostProcessor() { return new BeanPostProcessor() { /** * @company lihfinance.com * @author create by ZhaoShuai in 2020/3/21 * 在bean注冊前會被調(diào)用 * @param [bean, beanName] * @return java.lang.Object **/ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } /** * @company lihfinance.com * @author create by ZhaoShuai in 2020/3/21 * 在bean注冊后會被加載,本次在bean注冊成功后注入屬性值 * @param [bean, beanName] * @return java.lang.Object **/ @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { Class<?> clazz = bean.getClass(); if (!clazz.isAnnotationPresent(MyComponent.class)) { return bean; } Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (!field.isAnnotationPresent(Reference.class)) { continue; } Class<?> type = field.getType(); Object obj = applicationContext.getBean(type); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, obj); } return bean; } }; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
下面開始使用注解來看看效果:
package com.xiazhi.demo.service; import com.xiazhi.demo.annotation.MyComponent; import javax.annotation.PostConstruct; /** * @author ZhaoShuai * @company lihfinance.com * @date Create in 2020/3/21 **/ @MyComponent public class MyService { @PostConstruct public void init() { System.out.println("hello world"); } public void test() { System.out.println("測試案例"); } }
package com.xiazhi.demo.service; import com.xiazhi.demo.annotation.MyComponent; import com.xiazhi.demo.annotation.Reference; /** * @author ZhaoShuai * @company lihfinance.com * @date Create in 2020/3/21 **/ @MyComponent public class MyConsumer { @Reference private MyService myService; public void aaa() { myService.test(); } }
啟動類要引入配置文件:
import注解引入配置文件。
編寫測試類測試:
@SpringBootTest(classes = ApplicationRun.class) @RunWith(SpringRunner.class) public class TestDemo { @Autowired public MyConsumer myConsumer; @Test public void fun1() { myConsumer.aaa(); } }
以上就是關(guān)于Springboot如何實(shí)現(xiàn)自動裝配的內(nèi)容,如果你們有學(xué)習(xí)到知識或者技能,可以把它分享出去讓更多的人看到。