spring入門使用

代碼倉庫:https://gitee.com/DerekAndroid/springone.git

參考:https://www.w3cschool.cn/wkspring/pesy1icl.html

spring入門

1.創建類和屬性,包含set方法

package com.tutorialspoint;

public class HelloWorld {
    public String getMessage() {
        System.out.println("Your Message : " + message);
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    private String message;

}

2.Beans配置message

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
        <property name="message" value="Hello World!"/>
    </bean>
<beans>

3使用

public class MainApp {
    /**
     * Application Context 是 BeanFactory 的子接口,也被成爲 Spring 上下文
     */
    public static void main(String[] args) {
        //spring入門helloWorld
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
        obj.getMessage();

//        fileContext();
    }
}

Spring基於設置函數注入

1,TextEditorSet ,通過setSpellChecker方法注入spellChecker類

package com.injection;

public class TextEditorSet {
    private SpellCheckerSet spellChecker;

    public void setSpellChecker(SpellCheckerSet spellChecker) {
        System.out.println("Inside setSpellChecker." );
        this.spellChecker = spellChecker;
    }
    public void spellCheck(){
        spellChecker.checkSpelling();
    }
}

2,創建spellChecker類

package com.injection;

public class SpellCheckerSet {
    public SpellCheckerSet() {
        System.out.println("Inside SpellCheckerSet constructor.");
    }

    public void checkSpelling() {
        System.out.println("Inside checkSpelling.");
    }
}

3,Beans配置

<!--    基於設值函數的注入中,我們使用的是〈bean〉標籤中的〈property〉元素-->
    <bean id="TextEditorSet" class="com.injection.TextEditorSet">
        <property name="spellChecker" ref="SpellCheckerSet"/>
    </bean>
    <bean id="SpellCheckerSet" class="com.injection.SpellCheckerSet">
    </bean>

4.使用

package com.injection;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainInjection {
    public static void main(String[] args) {
        mainInjectionSet();
    }

//    基於設值函數注入中的 Beans.xml 文件
    private static void mainInjectionSet() {
        System.out.println("基於設值函數注入中的 Beans.xml 文件");
        ApplicationContext context =
                new ClassPathXmlApplicationContext("Beans.xml");
        TextEditorSet te= (TextEditorSet) context.getBean("TextEditorSet");
        te.spellCheck();
    }
}

Spring+JDBC+mysql使用

1.準備sql

 CREATE TABLE Student(
 ID   INT NOT NULL AUTO_INCREMENT,
 NAME VARCHAR(20) NOT NULL,
 AGE  INT NOT NULL,
 PRIMARY KEY (ID)
 );

2創建Student類

package com.mysql;

public class Student {
    private Integer age;
    private String name;
    private Integer id;
    public void setAge(Integer age) {
        this.age = age;
    }
    public Integer getAge() {
        return age;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getId() {
        return id;
    }
}

3.核心代碼:創建JDBC類,通過xml的形式mysql配置文件注入+mysql事務文件注入

package com.mysql;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;
import java.util.List;

public class StudentJDBCTemplate implements StudentDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;
    private PlatformTransactionManager transactionManager;

    public PlatformTransactionManager getTransactionManager() {
        return transactionManager;
    }

    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }


    @Override
    public void setDataSource(DataSource ds) {
        this.dataSource = ds;
        jdbcTemplateObject = new JdbcTemplate(ds);
    }

    @Override
    public void create(String name, Integer age) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            String SQL = "insert into Student (name, age) values (?, ?)";
            jdbcTemplateObject.update(SQL, name, age);
            System.out.println("Created Record Name = " + name + " Age = " + age);

            //模擬測試異常代碼
//            throw new RuntimeException("simulate Error condition") ;
//            int a =1/0;

            transactionManager.commit(status);
        } catch (DataAccessException e) {
            System.out.println("Error in creating record, rolling back");
            transactionManager.rollback(status);
        }


        return;
    }

    @Override
    public Student getStudent(Integer id) {
        String SQL = "SELECT * FROM Student WHERE id=?";
        Student student = jdbcTemplateObject.queryForObject(SQL, new Object[]{id}, new StudentMapper());

        return student;
    }

    @Override
    public List<Student> listStudents() {
        String SQL = "SELECT * FROM Student";
        List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
        return students;
    }

    @Override
    public void delete(Integer id) {
        String SQL = "delete FROM Student WHERE id=?";
        jdbcTemplateObject.update(SQL, id);
        System.out.println("Deleted Record with ID = " + id);
        return;
    }

    @Override
    public void update(Integer id, Integer age) {
        String SQL = "update Student set age = ? where id = ?";
        jdbcTemplateObject.update(SQL, age, id);
        System.out.println("Updated Record with ID = " + id);
        return;
    }
}

注入:


    <!--    mysql配置文件-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
        <property name="username" value="root"/>
        <property name="password" value="123"/>
    </bean>
    <!--    mysql事務文件-->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <bean id="studentJDBCTemplate" class="com.mysql.StudentJDBCTemplate">
        <!--        mysql配置文件注入-->
        <property name="dataSource" ref="dataSource"/>
        <!--        mysql事務文件注入-->
        <property name="transactionManager" ref="transactionManager"/>
    </bean>

使用

package com.mysql;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 Spring JDBC 示例
 CREATE TABLE Student(
 ID   INT NOT NULL AUTO_INCREMENT,
 NAME VARCHAR(20) NOT NULL,
 AGE  INT NOT NULL,
 PRIMARY KEY (ID)
 );
 * );
 */
public class MainAppJDBC {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("Beans.xml");
        StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");
        System.out.println("------Records Creation--------");
        studentJDBCTemplate.create("Zara", 11);
        studentJDBCTemplate.create("Nuha", 2);
        studentJDBCTemplate.create("Ayan", 15);
        System.out.println("------Listing Multiple Records--------");
        List<Student> students = studentJDBCTemplate.listStudents();
        for (Student record : students) {
            System.out.print("ID : " + record.getId());
            System.out.print(", Name : " + record.getName());
            System.out.println(", Age : " + record.getAge());
        }
        System.out.println("----Updating Record with ID = 2 -----");
        studentJDBCTemplate.update(2, 20);
        System.out.println("----Listing Record with ID = 2 -----");
        Student student = studentJDBCTemplate.getStudent(2);
        System.out.print("ID : " + student.getId());
        System.out.print(", Name : " + student.getName());
        System.out.println(", Age : " + student.getAge());
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章