在spring和springboot项目中main方法如何调用service方法

目录

1、在spring中调用service方法

2、在springboot中调用service方法

3、SpringBoot中给静态常量注入配置文件中的值

1、在spring中调用service方法

main方法:

public class App2 {
    public static void main(String[] args) {
        //读取Springboot配置文件
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //通过类型来获取类
        BookService bookService = (BookService) ctx.getBean(BookService.class);
        System.out.println(bookService);
        //执行service方法
        bookService.save();
    }
}

application:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启注解支持-->
    <context:component-scan base-package="com.rk"></context:component-scan>

</beans>

bookservice:

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    public void save() {
        System.out.println("book service save ...");
        bookDao.save();
    }
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }
}

2、在springboot中调用service方法

编写一个SpringUtil:

package com.yum;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtil.applicationContext == null){
            SpringUtil.applicationContext  = applicationContext;
        }

    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);

    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }
}

这样就可以从容器中获取组件了

main方法:

@SpringBootApplication
@MapperScan(basePackages = {"com.yum.mapper"})
public class TestCont {
    public static void main(String[] args) {
        SpringApplication.run(TestCont.class, args);
        ApplicationContext context = SpringUtil.getApplicationContext();
        LiveDataService liveDataService = context.getBean(LiveDataService.class);
        List<String> list = liveDataService.CheackGmv();
        System.out.println(list);
        System.out.println("完成");
    }
}

3、SpringBoot中给静态常量注入配置文件中的值

配置文件.yml:

aliyun: #自定义配置
  oss:
    endpoint: oss-cn-hangzhou.aliyuncs.com
    accessKeyId: xxx
    secret: xxx
    bucketName: xx-filerk

 工具类:

/**
 * @author :Rk.
 * @date : 2022/11/23
 */
@Component
public class ConstantOssPropertiesUtils implements InitializingBean {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.secret}")
    private String secret;

    @Value("${aliyun.oss.bucket}")
    private String bucket;

    public static String EDNPOINT;
    public static String ACCESS_KEY_ID;
    public static String SECRECT;
    public static String BUCKET;

    @Override
    public void afterPropertiesSet() throws Exception {
        EDNPOINT=endpoint;
        ACCESS_KEY_ID=accessKeyId;
        SECRECT=secret;
        BUCKET=bucket;
    }
}

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
springboot学习笔记 spring基础 Spring概述 Spring的简史 xml配置 注解配置 java配置 Spring概述 Spring的模块 核心容器CoreContainer Spring-Core Spring-Beans Spring-Context Spring-Context-Support Spring-Expression AOP Spring-AOP Spring-Aspects Messaging Spring-Messaging WEB Spring-Web Spring-Webmvc Spring-WebSocket Spring-Webmvc-Portlet 数据访问/集成(DataAccess/Intefration) Spring-JDBC Spring-TX Spring-ORM Spring-OXM Spring-JMS Spring的生态 Spring Boot Spring XD Spring Cloud Spring Data Spring Integration Spring Batch Spring Security Spring HATEOAS Spring Social Spring AMQP Spring Mobile Spring for Android Spring Web Flow Spring Web Services Spring LDAP Spring Session Spring项目快速搭建 Maven简介 Maven安装 Maven的pom.xml dependencies dependency 变量定义 编译插件 Spring项目的搭建 Spring Tool Suite https://spring.io/tools/sts/all IntelliJ IDEA NetBeans https://netbeans.org/downloads/ Spring基础配置 依赖注入 声明Bean的注解 @Component组件,没有明确的角色 @Service在业务逻辑层(service层) @Repository在数据访问层(dao层) @Controller在展现层(MVC→SpringMVC) 注入Bean的注解 @Autowired:Spring提供的注解 @Inject:JSR-330提供的注解 @Resource:JSR-250提供的注解 Java配置 @Configuration声明当前类是一个配置类 @Bean注解在方法上,声明当前方法的返回值为一个Bean AOP @Aspect 声明是一个切面 拦截规则@After @Before @Around PointCut JoinPoint Spring常用配置 Bean的Scope Singleton Prototype Request Session GlobalSession SpringEL和资源调用 注入普通字符 注入操作系统属性 注入表达式云算结果 注入其他Bean的属性 注入文件内容 注入网址内容 注入属性文件 Bean的初始化和销毁 Java配置方式 注解方式 Profile @Profile 通过设定jvm的spring.profiles.active参数 web项目设置在Servlet的context parameter 事件Application Event 自定义事件,集成ApplicationEvent 定义事件监听器,实现ApplicationListener 使用容器发布事件 Spring高级话题 Spring Aware BeanNameAware BeanFactoryAware
【资源说明】 1、基于Java+Springboot+MySQL+Thymeleaf 架构的电影聚合系统源码+数据库+项目说明.zip 2、该资源包括项目的全部源码,下载可以直接使用! 3、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末大作业和毕设项目,作为参考资料学习借鉴。 4、本资源作为“参考资料”如果需要实现其他功能,需要能看懂代码,并且热爱钻研,自行调试。 基于Java+Springboot+MySQL+Thymeleaf 架构的电影聚合系统源码+数据库+项目说明.zip > 一个采用 SpringBoot 架构的电影聚合 JavaWeb 项目,适用于 SpringBoot 练手项目 #### 二、运行环境 * IDEA * JDK 8 * MySQL([数据库链接:db_film](https://github.com/volewu/Film/blob/master/db_cms.sql)) #### 三、项目技术 * Spring && Spring Boot && Spring Sectuity * Spring Data Jpa * EsayUI + Bootstrap * thymeleaf * ckeditor * 运行截图 ![film](https://github.com/volewu/Film/blob/master/preview/film.gif?raw=true) ​ #### 四、姿势点 ##### 1、 SpringSecurity 得到登入的用户名 ```html th:text="${#httpServletRequest.remoteUser}" ``` ##### 2、thymeleaf 问题 ```html /*<![CDATA[*/ 不扫描该注释的代码 /*]]>*/ //时间转换 ${#dates.format(film.publishDate,'yyyy-MM-dd HH:mm:ss')} ``` ##### 3、jpa 格式化时间 [CustomDateSerializer.java](https://github.com/volewu/Film/blob/master/src/main/java/com/vole/film/util/CustomDateSerializer.java) ```java @JsonSerialize(using = CustomDateSerializer.class) public Date getPublishDate() { return publishDate; } ``` ##### 4、jpa Repository 自定义方法 [WebSiteInfoRepository.java](https://github.com/volewu/Film/blob/master/src/main/java/com/vole/film/repository/WebSiteInfoRepository.java) ```java // 1 代表第一个参数 @Query(value = "select * from t_info where film_id=?1", nativeQuery = true) List<WebSiteInfo> getByFilmId(Integer filmId); ``` ##### 5、jpa 模糊查询拼接 [FilmServiceImpl.java](https://github.com/volewu/Film/blob/master/src/main/java/com/vole/film/service/impl/FilmServiceImpl.java) ```java @Override public List<Film> list(Film film, Integer page, Integer pageSize) { Pageable pageable = new PageRequest(page, pageSize, Sort.Direction.DESC, "publishDate"); Page<Film> filmPage = filmRepository.findAll((root, criteriaQuery, cb) -> { Predicate predicate = cb.conjunction(); if (film != null) { if (Str
计算机科学与技术系 实 验 报 告 专业名称 计算机科学与技术 课程名称 Android嵌入式软件开发 项目名称 Service 后台服务 班 级 计科一班 学 号 姓 名 同组人员 无 实验日期 2016.10.11 一、实验目的与要求: 【实验目的】 掌握 Service 的启动和停止方法,熟悉 Service 的生命周期,掌握 NotificationManager的使用方法。 【实验要求】 1、 练习使用两种方式启动 Service,并通过 Logcat 观察 Service 的生命周期 2、 练习使用 NotificationManager 发送通知消息到状态栏 3、 完成实验报告 二、实验内容 1、 新建 Android 应用程序项目 ServiceTest; 2、 业务逻辑代码与布局文件分别是MainActivity.java 和activity_main.xml。 实验结果截图: 图表 1 普通方式创建Service 图表 2 发送并接收消息 图表 3 关闭Service 图表 4 绑定创建Service 图表 5 接收消息 图表 6 解绑定 三、实验分析与小结: Service是安卓的四大组件之一,长期运行在后台处理事件和数据。与Activity不同,它 是不能与用户交互的,不能自己启动的,需要调用Context.startService()来启动,运 行后台,如果我们退出应用时,Service进程并没有结束,它仍然在后台行。Service有 两种启动方式,对应的,有两种停止方式。 【思考题】 【1】Service的两种启动方式是什么?对应的停止方式是什么? Startservice(普通启动方式)和bindservice(绑定方式)都可以启动service,对应 的停止方式分别为stopService()和onUnbind()。 【2】Service的6个回调函数是什么? onCreate()、onStart()、onStartCommand()、onDestroy()、onBind()、onUnbind()。 得分(百分制) ----------------------- Android实验五全文共6页,当前为第1页。 Android实验五全文共6页,当前为第2页。 Android实验五全文共6页,当前为第3页。 Android实验五全文共6页,当前为第4页。 Android实验五全文共6页,当前为第5页。 Android实验五全文共6页,当前为第6页。
【资源说明】 1、基于SpringBoot的图书馆管理系统源码+数据库+项目说明(毕设).zip 2、该资源包括项目的全部源码,下载可以直接使用! 3、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末大作业和毕设项目,作为参考资料学习借鉴。 4、本资源作为“参考资料”如果需要实现其他功能,需要能看懂代码,并且热爱钻研,自行调试。 # 一、项目介绍 + 项目名称:Sirius天狼图书馆管理系统(Web) + maven依赖:<br> org.springframework.boot<br>     spring-boot-starter-data-mongodb<br>     spring-boot-starter-data-redis<br>     spring-boot-starter-mail<br>     spring-boot-starter-thymeleaf<br>     spring-boot-starter-web<br>     spring-boot-starter-test<br> org.mybatis.spring.boot<br>     mybatis-spring-boot-starter<br> mysql:<br>     mysql-connector-java<br> org.projectlombok:<br>     lombok<br> com.alibaba:<br>     druid-spring-boot-starter<br> + plugin插件: org.mybatis.generator:<br>     mybatis-generator-maven-plugin<br> 其他默认插件 + 打包方式:jar/war + 目录结构:<br> --main:代码<br>   | comtroller:控制器层<br>     | user:用户端控制器<br>     | administrator:管理员端控制器<br>     | main:公共页面控制器<br>   | dao:数据库永久dao接口层<br>     | mysql:mysql端数据库接口<br>     | redis:redis端数据库接口<br>     | mongo:MongoDB端数据库接口<br>   | domain:实体类层<br>   | enums:枚举类<br>   | filter:过滤器层<br>     | conf:过滤器层配置类<br>   | service:服务层<br>     | impls:实现类<br>     | interfaces:接口类<br>   | transactor:拦截器层<br>     | conf:拦截器层配置类<br>   | tools:工具类<br>   | exceptions:自定义异常类<br> --resources:资源文件(所有的xml等类型的配置文件放在这里)<br>   | mapper:数据库SQL语句mapper文件<br>   | static:静态文件<br>     | css:css文件<br>     | js:JavaScript文件<br>     | images:图片文件<br>   &

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rk..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值