Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize springboot starter

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

How to customize springboot starter, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

Custom springboot starter

Take a look at a demo. Demo implements two functions:

Aop in Aspectj mode is used to monitor the parameters of certain functions.

Define your own configuration class, read the parameters we configured in yml or properties, and provide a service to get the results we read.

Here is the example project starter.

Starter

After reading the automatic configuration principle, you should know that the META-INF/spring.facotires guy is the focus of the configuration, a lot of our things are in this. Therefore, of course, our own stater can not do without this configuration file, first paste a project structure.

Spring-boot-myaop-starter ├─ pom.xml ├─ spring-boot-myaop-starter.iml └─ src/main ├─ java └─ resources └─ META-INF └─ spring.factoriesAOP section

First according to the normal project to configure some of the configuration, first write an AspectJ.

Package com.wt.myaop.aspect;@Aspect@Componentpublic class MyAspect {@ Pointcut ("@ annotation (myAnno)") public void myAspectPointCut (MyAopAnnotation myAnno) {} @ Before ("myAspectPointCut (myAnno)") public void performanceTrance2 (JoinPoint joinPoint, MyAopAnnotation myAnno) throws Throwable {System.out.println ("- myaop-starter args monitor start-") Object [] args = joinPoint.getArgs (); Class [] types = myAnno.argTypes (); for (int I = 0; I < Math.min (args.length, types.length); iTunes +) {System.out.println ("type:" + types [I] + "arg:" + args [I]) } System.out.println ("- myaop-starter args monitor end-");}}

We use @ Before here, in which we get all the parameters, then print out the types and values of all the parameters, and output the log before and after the method, which is relatively simple.

Then let's take a look at pointCut, which is annotation-based, so that other projects can use this starter directly as annotations and are not intrusive to other projects. So, we also need to define an annotation.

Package com.wt.myaop.anno;@Target (ElementType.METHOD) @ Documented@Retention (RetentionPolicy.RUNTIME) public @ interface MyAopAnnotation {Class [] argTypes () default {};}

There are attributes in the annotation, which are used to define the type order of method parameters, of course, they are not needed, and they are put here just for convenience.

Attribute reading part

We need to use an annotation @ ConfigurationProperties of springboot to read the attribute. Let's take a look at this configuration class. In order to shorten the length of the code, there is no getter/setter method posted.

Package com.wt.myaop.config;@ConfigurationProperties (prefix = MyConfig.MY_PREFIX) public class MyConfig {public static final String MY_PREFIX = "myconfig"; / * * the value can be obtained normally without this annotation * / @ NestedConfigurationProperty private UserConfig user; private String job;}

In the code, we define a constant MY_PREFIX, which is the prefix in the configuration file. Springboot will read the configuration of this prefix and inject it into this entity. Of course, the configuration will certainly not be configured in our starter project, but in the project we actually use. Otherwise, I might as well just write to death, right, hee hee.

In addition to the basic attribute, an entity attribute, UserConfig, is provided. Let's take a look at this.

Package com.wt.myaop.config;public class UserConfig {private String username; private Integer age; private String sex;}

Now that we have the receiving entity of the configuration information, let's define a service. The purpose of this service is to inject the entity and then output the configuration information to check that our configuration is in effect. The interface of service will not be posted, ha, but only the implementation class.

Package com.wt.myaop.service;public class MyConfigServiceImpl implements MyConfigService {private final MyConfig myconfig; public MyConfigServiceImpl (MyConfig myConfig) {this.myconfig = myConfig;} @ Override public void printMyConfig () {System.out.println (myConfig);}}

Looking at the constructor and properties, the constructor injects our configuration. Of course, if we need to use this service, we need to manually inject this configuration to ensure that when service is instantiated, the myconfig is not null. The method inside is very simple, only printing our configuration class MyConfig.

Starter, is it over like this? Of course not, you can feel that all of these are not much different from the ordinary project configuration, it is very simple.

Recall that the core of our automatic configuration is something called xxxAutoConfiguration? Oh, in spring.vactories!

All right, come on, start defining our own AutoConfiguration.

Package com.wt.myaop.autoconfig;@Configuration@ComponentScan ({"com.wt.myaop.aspect"}) @ AutoConfigureAfter (AopAutoConfiguration.class) @ EnableConfigurationProperties (MyConfig.class) public class MyArgsMonitorAopAutoConfig {private MyConfig myConfig; public MyArgsMonitorAopAutoConfig (MyConfig myConfig) {this.myConfig = myConfig;} @ Bean public MyConfigService getMyConfigService () {return new MyConfigServiceImpl (myConfig);}}

Now let's take a look at what this category has.

@ Configuration: indicates that this class is a configuration class; @ ComponentScan: indicates the package that needs to be scanned, and you can see that the above scanned package contains the configuration of Aspect annotation, of course, using aop is essential; @ AutoConfigureAfter: indicates that the current class needs to be configured after some automatic configuration is completed; @ EnableConfigurationProperties: what does it mean to provide support for @ ConfigurationProperties annotation? To explain this, register the @ ConfigurationProperties annotated classes (MyConfig) as bean to support dependency injection. These classes themselves will not be registered as bean. Of course, we can annotate the configuration class with @ Component. Using this annotation can be used when we need a configuration class to register as bean, which is less intrusive and avoids adding @ Component annotations to the configuration class.

You can see from the above code that our configuration class MyConfig is injected into MyArgsMonitorAopAutoConfig through constructors, while MyArgsMonitorAopAutoConfig is a configuration class that configures MyConfigService in the form of @ Bean.

It looks like a simple answer, but it's actually very simple. AutoConfiguration's configuration class is fine. Introducing this class is tantamount to introducing a Myconfig configuration class and a MyConfigService that we can use.

Automatically configured classes are available and need to be put into spring.factories to take effect.

# META-INF/spring.factoriesorg.springframework.boot.autoconfigure.EnableAutoConfiguration=com.wt.myaop.autoconfig.MyArgsMonitorAopAutoConfig

In this way, the starter part is complete.

Tips: automatic configuration is actually very simple. Put all the required configurations into a project called starter, and then create an automatic configuration class for XxxAutoConfiguration, and configure all the required configurations in this class. Finally, just add this automatic configuration class to META-INF/spring.factories, isn't it easy, hee hee.

Demo

In fact, demo is also used to analyze the source code before that project, there is an address below. Let's focus on configuring and starting our own starter.

Here is the example project demo.

Once you have starter, use the mvn clean install command to install its jar locally.

Introduce this dependency into the demo project.

Com.wt.starter spring-boot-myaop-starter 1.0-SNAPSHOT is configured using MyConfig

We have a MyConfig configuration in starter, right? well, now we can define it in the yml or properties file. I use yml here.

Myconfig: job: programer user: username: wt age: 25 sex: real_man

Note that our prefix is myconfig, and the following job and user are attributes of the entity class MyConfig, because user is an entity class, so its attribute username,age,sex is also listed below. You can go to the previous MyConfig and UserConfig to compare the attributes of the two entities.

Use parameters to monitor AOP

In addition to the MyConfig above, there is also a function of aop to monitor parameters in starter, which we will use right away.

Define a service first, and the interface will not be posted.

Servicepublic class MyStarterServiceImpl implements MyStarterService {@ Override @ MyAopAnnotation (argTypes = {String.class}) public void helloStarter (String msg, Long currentTime) {System.out.println ("- hello starter,msg =" + msg + ", currentTime =" + currentTime);}}

Method is annotated MyAopAnnotation in order to be intercepted by aop in starter.

Then define a controller for testing.

@ RestController@RequestMapping ("/ starter") public class MyStarterController {@ Autowired private MyConfigService myConfigService; @ Autowired private MyStarterService myStarterService; @ RequestMapping ("/ test") public Object starter () {myConfigService.printMyConfig (); myStarterService.helloStarter ("wt", System.currentTimeMillis ()); return "success";}}

Pay attention to the distinction, MyConfigService is in our starter, MyStarterService is in our demo project.

Start the project now and visit http://127.0.0.1:8080/starter/test to try!

Take a look at the output (copied without using a screenshot):

MyConfig {user=UserConfig {username='wt', age=25, sex='real_man'}, job='programer'}-myaop-starter args monitor start-type:class java.lang.Stringarg:wt-myaop-starter args monitor end----hello starter Msg = wt,currentTime = 1564472340205

The first line is the output of myConfigService.printMyConfig (), which outputs our configuration in yml, which shows that our configuration was successfully assigned to MyConfig. It means that our config is working.

The second and fourth lines are the output before and after the aop part of the starter @ Before method. The third line in the middle outputs the parameter type String and the parameter value wt. Because only one String.class is specified on the note, the second parameter is not output here, so the specific logic is to look at the @ Before method of aop in the starter.

The last line is the output of the enhanced method, printing msg and currentTime.

Now you can imagine the Datasource configuration of springboot in a yml or properties file!

If you see here, the starter section is over.

After reading the above, have you mastered how to customize springboot starter? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report