Recently want to do some Web projects to fill the next spare time, the first thought of the use of Springboot framework, after all, convenient and fast
First of all: go here http://start.spring.io/directly constructs a springboot initialized project framework
Then: Select the appropriate dependency package on the page, then click the Build button, then download and import into the IDE, now like to use idea
So a simple Springboot project was built.
Finish the crap and then want to experience the use of redis in spring;
Then create a new class directly, and then @Autowired automatically inject the Redistemplate class, which, of course, adds @Component annotations to this class.
But here's the problem, creating a method under this class, and then calling Redistemplate in the method, the hint is null, which is why?
Here are a few more useful ways to try out a variety of solutions that are shared online:
1. Note is not scanned, the problem may be that the Springboot startup class is not placed under the outermost package root directory
Because springboot automatically scans for annotations contained in all child packages of the boot class, if the startup class is misplaced, it causes the annotation to be scanned
For specific logic, see
The parsing of the annotations contained in @SpringBootApplication annotations is the logic of scanning annotations
2. When invoked, the object used is new, not spring automatically injected, not managed by spring, so of course null
For example: A redistemplate is injected into Class A and then, after the Springboot project is started, a main method is created in Class A, and then in Main, new A (); To create an instance of a, and then a.redistemplate the call, gets a null value
Therefore: The solution is if you want to use the @Autowired to inject some springboot automatic management tools, such as redistemplate/jdbctemplate, etc., or directly in the startup class to inject, but this use less, Typically creates a new class and injects it inside,
However, if you want to use this class and then use it in subclasses, such as using Redistemplate and JdbcTemplate, you can create a Datasourceconfig class and then automatically inject Redistemplate and JD Bctemplate then create a new two methods, Getredistemplate () and Getjdbctemplate ()
The corresponding template is returned and then used in DAO to inherit Datasourceconfig directly, then use both getredistemplate () and Getjdbctemplate () methods to get Operation of data to Redis and JdbcTemplate
Above only for I recently encountered a relatively silent bug resolved after the memo, do not commit
But if you just contact Springboot, you may encounter this kind of problem, welcome to discuss together
If help to Yimeimei, then boundless beneficence
About automatic injection in the Springboot project, but a bug with an empty value