标签:spring boot springframework ComponentScan org import ServletComponentScan com 注解
ComponentScan
这个注解可以扫描带@Component的类。众所皆知,@RestController和@Configuration和@Service和@Configuration等都有带Component这个注解。所以如果要注入controller和service等,我们可以直接在类上面注解下,并且开启ComponentScan,这样会自动装载并注入这个实例,我们使用的时候可以直接@Autowired使用,下面以controller为栗子:
a:首先在spring boot启动入口开启自动扫描Component的注解(在类上面使用@ComponentScan),这个注解可以配置扫描的路径,我这里配置com.xx,也就是我把controller都放这里,系统会自动注入
由于@ComponentScan其实在SpringBootApplication这里已经有了,我们可以直接用scanBasePackages扫描的路径。即不用ComponentScan这个注解了,取而代之的是用SpringBootApplication
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @SpringBootApplication(scanBasePackages = "com.xx") @ServletComponentScan(basePackages="com.example.demo")public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
b:controller层编写
package com.xx; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author zhujianming * @date 2021-05-10 10:24 */ @RestController public class PPController { @RequestMapping("/testp") public String hello(){ return"Hello world!"; } }
这样直接访问localhost:8080/testp就会返回json了
ServletComponentScan
上面一步在spring boot中启动类加了@ServletComponentScan(basePackages="com.example.demo"),所以扫描路径是com.example.demo,我们下一步在com.example.demo编写个Servlet作为案例
编写@WebServlet
package com.example.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name="TestServlet",urlPatterns="/test") public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doGet"); } }
这样直接访问/test就会在控制台输出doGet,当然这个注解也会扫描Filter等控件,有空可以去试试
标签:spring,boot,springframework,ComponentScan,org,import,ServletComponentScan,com,注解 来源: https://www.cnblogs.com/nming/p/14750200.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。