SpringBoot配置非含main类的Controller的注解

刚开始接触SpringBoot,看了一些入门的资料,但是比较有意思的是从最简单的hello world到后面代码都不变了啊23333,要改注解的


不是在含main的类里增加其他包含RequestMapping的controller的类的定义,需要对含main函数的类进行注解,以指向controller类。


方法有两种,一种是用

@ComponentScan(value = {"controller所在包名"})

另一种是用

@SpringBootApplication

例如含RequestMapping的类:

package id0.id1.controller;

import java.util.Date;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/")
public class Ctl {
    @RequestMapping(value="/", method=RequestMethod.GET)
    String home(){
        return "Hello world";
	}
		
	@SuppressWarnings("deprecation")
	@RequestMapping("/now")
	String getTime(){
		return "Current time: " + (new Date()).toLocaleString();
	}
}

要让这个生效,就需要对含main的类增加注解,ComponentScan方式:

package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(value = {"com.test.controller"})
@EnableAutoConfiguration
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        SpringApplication.run(App.class, args);
    }
}

另一种SpringBootApplication方式:

package com.test.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableAutoConfiguration
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        SpringApplication.run(App.class, args);
    }
}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值