【无标题】springboot

SpringApplication.run(Application.class, args);

run方法执行后会得到spring容器,spring容器在根据添加到类上的注解操作、执行类。

两种容器配置方式 xml方式 、config方式

xml

spring xml配置容器 spring中提到过ApplicationContext ctx=new ClassPathXmlApplicationContext();

config

javaconfig配置容器 ApplicationContext ctx =new AnnotationConfigApplicationContext(SpringConfig. class)
AnnotationConfigApplicationContext类

JavaConfig 注入实例三种方式

1.bean

@Configuration:放在类的上面, 这个类相当于 xml 配置文件,可以在其中声明 bean
@Bean:放在方法的上面, 方法的返回值是对象类型, 这个对象注入到 spring ioc 容器

@Configuration
public class SpringConfig {
    @Bean
    public Student createStudent(){
    Student s1  = new Student();
    }

2.@ImportResource

@ImportResource 是导入 xml 配置

@ImportResource(value = "classpath:applicationContext.xml")位于配置类上

3.@PropertyResource

@PropertyResource 是读取 properties 属性配置文件

@PropertySource(value = "classpath:config.properties")位于配置类上

以上还在springzhong

以下在springboot中

springboot重要注解

@SpringBootApplication 是 一 个 复 合 注 解 , 是 由

@SpringBootConfiguration, @EnableAutoConfiguration ,@ComponentScan 联合在一起组
成的。

@SpringBootConfiguration : 就 是 @Configuration 这 个 注 解 的 功 能 , 使 用

@SpringBootConfiguration 这个注解的类就是配置文件的作用。

@EnableAutoConfiguration:开启自动配置, 把一些对象加入到 spring 容器中。

@ComponentScan:组件扫描器扫描@Componentscan注释的类,可以得到该类的实例对象

Spring Springt Boot 核心配置文件

Spring Boot 的核心配置文件用于配置 Spring Boot 程序,名字必须以 application 开始

.properties 默认采用改配置文件

server.port=9092
server.servlet.context-path=/boot

yml

yml 采用一定的空格、换行等格式排版进行配置。

server:
port: 9091
servlet:
context- - path: /boot

多环境配置

自定义配置(也就是赋值)

@Value

 @Value("${server.port}") 可直接赋值
    private Integer port;

 @Value("${school.name}") , school.name来自 application.properties(yml)
配置文件中
 school.name=你好


 读取配置文件数据
 @Value("${school.name}")
private String name;

@ConfigurationProperties 用于类上,用配置文件中的值给该类的属性赋值

注释
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {}
注入(赋值)
@Resource
    private SchoolInfo info;

获取容器对象并从容器中取出对象

获取容器对象
ApplicationContext ctx = SpringApplication.run(Application.class, args);


## 从容器者获取对象
		UserService userService = (UserService) ctx.getBean("userService");

		userService.sayHello("李四");

userService类 标明可注入容器
@Service("userService")
public class UserServiceImpl implements UserService {

CommandLineRunner类

开发中可能会有这样的情景。需要在容器启动后执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot 给我们提供了两个接口来帮助我们实现这种需求。这两个接口分别为 CommandLineRunner 和 ApplicationRunner。他们的执行时机为容器启动完成的时候。
这两个接口中有一个 run 方法,我们只需要实现这个方法即可。这两个接口的不同之处在 于 : ApplicationRunner 中 run 方 法 的 参 数 为 ApplicationArguments , 而CommandLineRunner接口中 run 方法的参数为 String 数组

@SpringBootApplication
public class Application implements CommandLineRunner {
    @Resource
	private HelloService helloService;

	public static void main(String[] args) {
		System.out.println("准备创建容器对象");
		//创建容器对象
		SpringApplication.run(Application.class, args);
		System.out.println("容器对象创建之后");
	}

	@Override
	public void run(String... args) throws Exception {

		String str  = helloService.sayHello("lisi");
		System.out.println("调用容器中的对象="+str);
		//可做自定义的操作,比如读取文件, 数据库等等
		System.out.println("在容器对象创建好,执行的方法");
	}
}

使用拦截器

自定义拦截器

实现HandlerInterceptor

public class LoginInterceptor implements HandlerInterceptor  {
	重写preHandle
	@Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("执行了LoginInterceptor的preHandle");
        return true;

在配置类中调用拦截器

自定义配置类MyAppConfig
WebMvcConfigurer配置接口

@Configuration
public class MyAppConfig implements WebMvcConfigurer {

    //添加拦截器对象, 注入到容器中
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //创建拦截器对象
        HandlerInterceptor interceptor = new LoginInterceptor();

        //指定拦截的请求uri地址
        String path []= {"/user/**"};
        //指定不拦截的地址
        String excludePath  [] = {"/user/login"};
	//调用拦截器
	//registry类
        registry.addInterceptor(interceptor)
                .addPathPatterns(path)
                .excludePathPatterns(excludePath);

    }
}		

使用servelet 意义在于可使用tomcat中的类

先写一个servlet

public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       。。。
    }
}

创建配置类,

配置类加了@Configuration,spring会把该类加到容器中,自动配置,在配置类中,创建ServletRegistrationBean对象,ServletRegistrationBean对象是一个对servlet进行配置的对象。此时使用ServletRegistrationBean对象,对servlet进行请求路径等功能的配置;

@Configuration
public class WebApplictionConfig {
    //定义方法, 注册Servlet对象
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet( new MyServlet());
        bean.addUrlMappings("/login","/test"); // <url-pattern>
        return bean;
    }

使用过滤器filter

与使用servelet思路一样

创建filter

public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("执行了MyFilter,doFilter ");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

创建controller

public class CustomFilterController {

    @RequestMapping("/user/account")
    @ResponseBody
    public String userAccount(){
        return "user/account";
    }

配置 filter 创建filter配置类对象对filter进行配置,FilterRegistrationBean bean = new FilterRegistrationBean();

@Configuration
public class WebApplicationConfig {

    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean bean  = new FilterRegistrationBean();
        bean.setFilter( new MyFilter());
        bean.addUrlPatterns("/user/*");
        return bean;
    }
}

运行就可以使用filter

字符集过滤器使用 -------CharacterEncodingFilter

与servelet使用思路一样

FilterRegistrationBean对象setFilter(CharacterEncodingFilter对象)

在 application.properties , 禁用 Spring Boot 中默认启用的过滤器`

server.servlet.encoding.enabled=false

在 application.properties 设置过滤器

#设置 spring boot 中 CharacterEncodingFitler 的属性值
server.servlet.encoding.enabled= true
server.servlet.encoding.charset=utf-8
#强制 request, response 使用 charset 他的值 utf-8
server.servlet.encoding.force= true

@Mapper Scan

在 Dao 接口上面加入@Mapper,需要在每个接口都加入注解。 当 Dao 接口多的时候不方便。
可以在主类上添加注解包扫描:@MapperScan(“com.bjpowernode.dao”),这样就不用一个接口加一个@Mapper了
意思就是批量导入一个包中的所有映射接口

@SpringBootApplication
@MapperScan(basePackages = {"com.bjpowernode.dao","com.bjpowernode.mapper"})
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}

mapper.xml文件与java文件分开

mapper 文件放在 resources 目录下, java 代码放在 src/main/java。
实现步骤:
➢ 在 resources 创建自定义目录,例如 mapper, 存放 xml 文件
➢ 把原来的 xml 文件剪切并拷贝到 resources/mapper 目录
➢ 在 application.properties 配置文件中指定映射文件的位置,这个配置只有接口和映
射文件不在同一个包的情况下,才需要指定。

 #指定mapper文件的位置
mybatis.mapper-locations=classpath:mapper/*.xml

事务支持

➢ 在入口类中使用注解 @EnableTransactionManagement 开启事务支持

➢ 在访问数据库的 Service 方法上添加注解 @Transactional 即可

接口架构风格 —restful

比如我们要访问一个 http 接口:http://localhost:8080/boot/order?id=1021&status=1
采用 RESTFul 风格则 http 地址为:http://localhost:8080/boot/order/1021/1

result注释

@PathVariable

获取url中的数据

@PostMapping

处理和接收post请求

@DeleteMapping

@PutMapping

@GetMapping

实例

@RestController
public class MyRestController {
//http://localhost:8080/myboot/student/1002
    @GetMapping("/student/{stuId}")
    public String  queryStudent(@PathVariable("stuId") Integer  studentId){
        return "查询学生studentId="+studentId;
    }
    

resutfu风格访问与普通访问不能通用

启用 HiddenHttpMethodFilter 这个过滤器, 支持 post 请求转为 put,delete
spring.mvc.hiddenmethod.filter.enabled=true

使用redis

Spring Boot 中使用 RedisTemplate 模版类操作 Redis 数据
spring boot 会在容器中创建两个对象 RedisTemplate ,StringRedisTemplate

使用RedisTemplate

通过redisTemplate.opsForValue();得到可以操作redis数据库的对象,就可以操作数据库了

ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("myname","lisi");

使用StringRedisTemplate对象

    stringRedisTemplate.opsForValue().set(k,v);

流程

pom.xml添加依赖

< dependency>
< groupId>org.springframework.boot</ groupId>
www.bjpowernode.com  69 / 137 Copyright©动力节点
< artifactId>spring-boot-starter-data-redis</ artifactId>
</ dependency>

核心配置文件 核心配置文件 application .properties

#指定 redis
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=123456

调用

打包

war包

打成war包,使用 Spring Boot 的 maven 插件将 Springboot 程序打成 war 包,单独部署在 tomcat 中运行(上线部
署 常用)部署在tomcat目录webapps 下

jar包

用 maven 将 Spring Boot 安装为一个 jar 包,使用 Java 命令运行
java -jar springboot-xxx.jar

thymeleaf

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值