如何在Spring Boot应用程序中不启动Spring服务器的情况下调用该方法

发布于 2025-01-16 10:23:38 字数 2536 浏览 3 评论 0原文

我创建了一个 Spring Boot 项目,但后来意识到我不想在服务器上运行该应用程序,只想在 main 方法中实现我的逻辑。 到目前为止我已经完成了,但我似乎无法弄清楚我错过了什么。

我有一个 MainLogic.java 类

    @Configuration
public class MainLogic {
        
    JdbcTemplate jdbcTemplate;
    
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    private String sqlQuery = "";
    
    public String getID(@RequestParam String id, @RequestParam(required=false) String date){
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");   
        dateFormat.setLenient(false);
        String path = "";
      
            sqlQuery= "SELECT i.abc_id as id"
                    + "FROM ABCDetail i  \n"
                    + "WHERE i.abc_id = "+id+"\n"
        }
        
        #46: List<ABC> ABCdetails = jdbcTemplate.query(sqlQuery, new BeanPropertyRowMapper<ABC>(ABC.class));
        ABCdetails.toString();
         final StringBuilder textData = new StringBuilder();
            final String headers = "ID";
            textData.append(headers).append("\n");
            for (final ABC abcDetail : ABCdetails) {
                final String line = ((abcDetail.getID()==null)?"": abcDetail.getID()) + "\t" + ((abcDetail.getEXT_TYPE()==null)?"";
                textData.append(line).append("\n");
            }
            try {
            File tempDir = new File(System.getProperty("java.io.tmpdir"));
            File tempFile = File.createTempFile("output", ".tmp", tempDir);
            FileWriter fileWriter = new FileWriter(tempFile, true);
            System.out.println(tempFile.getAbsolutePath());
            path = tempFile.getAbsolutePath();
            BufferedWriter bw = new BufferedWriter(fileWriter);
            bw.write(textData.toString());
            bw.close();
            
            }catch (Exception e) {
                // TODO: handle exception
            }
        return path;
        }
 

和我的主类,

public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(MainLogic.class);
        MainLogic ml = ctx.getBean(MainLogic.class);
        String newPath = "";
        if(args.length > 0) {
            try {
                System.out.println("Passing the argument to the controller: "+ ml.getID(args[0], args[1]));
        }

我在第 46 行 MainLogic 中遇到空指针异常,有人可以帮助我吗? 或者有人可以建议我更好地做到这一点吗? 我是JAVA新手。

I created a spring boot project, but then realized I dont want to run the app on the server, just wanted to implement my logic in the main method.
I have done so far, and I cant seem to figure out what am I missing.

I have a class MainLogic.java

    @Configuration
public class MainLogic {
        
    JdbcTemplate jdbcTemplate;
    
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    private String sqlQuery = "";
    
    public String getID(@RequestParam String id, @RequestParam(required=false) String date){
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");   
        dateFormat.setLenient(false);
        String path = "";
      
            sqlQuery= "SELECT i.abc_id as id"
                    + "FROM ABCDetail i  \n"
                    + "WHERE i.abc_id = "+id+"\n"
        }
        
        #46: List<ABC> ABCdetails = jdbcTemplate.query(sqlQuery, new BeanPropertyRowMapper<ABC>(ABC.class));
        ABCdetails.toString();
         final StringBuilder textData = new StringBuilder();
            final String headers = "ID";
            textData.append(headers).append("\n");
            for (final ABC abcDetail : ABCdetails) {
                final String line = ((abcDetail.getID()==null)?"": abcDetail.getID()) + "\t" + ((abcDetail.getEXT_TYPE()==null)?"";
                textData.append(line).append("\n");
            }
            try {
            File tempDir = new File(System.getProperty("java.io.tmpdir"));
            File tempFile = File.createTempFile("output", ".tmp", tempDir);
            FileWriter fileWriter = new FileWriter(tempFile, true);
            System.out.println(tempFile.getAbsolutePath());
            path = tempFile.getAbsolutePath();
            BufferedWriter bw = new BufferedWriter(fileWriter);
            bw.write(textData.toString());
            bw.close();
            
            }catch (Exception e) {
                // TODO: handle exception
            }
        return path;
        }
 

and my main class

public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(MainLogic.class);
        MainLogic ml = ctx.getBean(MainLogic.class);
        String newPath = "";
        if(args.length > 0) {
            try {
                System.out.println("Passing the argument to the controller: "+ ml.getID(args[0], args[1]));
        }

I am getting a null pointer exception in MainLogic at line #46, can someone please help me.
or can anyone suggest me a better to do this?
I am new to JAVA.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等风也等你 2025-01-23 10:23:38

Spring boot bean有一个生命周期过程。如果不启动 Spring Boot,您将获得依赖项的空指针。如JdbcTemplate jdbcTemplate; 你必须手动创建bean。如果没有 Spring Boot 启动,它不会被 application.properties 配置。

Bean 的生命周期

Bean 的生命周期

您可以创建一个简单的 maven/Gradle 项目并像这样连接 jdbc。

import java.sql.*;  
class MysqlCon{  
public static void main(String args[]){  
try{  
  Class.forName("com.mysql.jdbc.Driver");  
  Connection con=DriverManager.getConnection(  
  "jdbc:mysql://localhost:3306/sonoo","root","root");  
  //here sonoo is database name, root is username and password  
  Statement stmt=con.createStatement();  
  ResultSet rs=stmt.executeQuery("select * from emp");  
  while(rs.next())  
  System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  
  "+rs.getString(3));  
  con.close();  
  }catch(Exception e){ System.out.println(e);}  
 }  
}  

Spring boot bean has a life cycle process. Without starting spring boot, you will get null pointer for your dependencies. Such as JdbcTemplate jdbcTemplate; You have to create the bean manually. It won't be configured by application.properties without spring boot start up.

Life Cycle of Bean

Life Cyle of Bean

You can create a simple maven/Gradle project and connect jdbc like this.

import java.sql.*;  
class MysqlCon{  
public static void main(String args[]){  
try{  
  Class.forName("com.mysql.jdbc.Driver");  
  Connection con=DriverManager.getConnection(  
  "jdbc:mysql://localhost:3306/sonoo","root","root");  
  //here sonoo is database name, root is username and password  
  Statement stmt=con.createStatement();  
  ResultSet rs=stmt.executeQuery("select * from emp");  
  while(rs.next())  
  System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  
  "+rs.getString(3));  
  con.close();  
  }catch(Exception e){ System.out.println(e);}  
 }  
}  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文