Пружинная структура создается из -за сложности разработки программного обеспечения. Spring использует базовые джавабейцы, чтобы делать вещи, которые ранее возможны только EJB. Тем не менее, цель весны не ограничивается разработкой на стороне сервера. С точки зрения простоты, тестируемости и свободной связи, большинство приложений Java могут извлечь выгоду из Spring. Пружина представляет собой легкую управляющую инверсию (IOC) и сечение, ориентированная (AOP) структура контейнера.
◆ Цель: решить сложность разработки предприятия применения
◆ Функция: используйте базовый Javabean вместо EJB и предоставляет больше функций корпоративных приложений
◆ Применение: любое приложение Java
Инверсия контроля (МОК в аббревиатуре английского языка) дает право создавать объекты в рамках, которая является важной особенностью структуры и не является специальным термином для объектно-ориентированного программирования. Он включает в себя инъекцию зависимостей и поиск зависимости. На традиционном бизнес -уровне, когда необходимы ресурсы, на бизнес -уровне обнаруживаются новые ресурсы, так что связь (взаимозависимость и корреляция между программами) выше. Теперь передайте новую часть пружине, чтобы достичь высокой сплоченности и низкой связи. Короче говоря: первоначально, когда был вызван уровень слоя DAO или уровня обслуживания, приложение использовало новое, и теперь новые права были переданы на весну, и какие ресурсы были получены с весны!
1. Загрузите пакет JAR -зависимости, необходимый для рамки
Официальный весенний веб -сайт: http://spring.io/
Загрузите пакет JAR: http://repo.springsource.org/libs-release-local/org/springframework/spring
2. Импорт базовой пакет JAR
Фактически, основные банки с основными банками включают бобы; контекст; ядро; пакеты выражений, а другие зависят от журналов log4j. Конечно, весенние банки больше, чем это, они добавляются медленно на более поздней стадии.
3. Настройка файла конфигурации log4j
Файл журнала определен в каталоге SRC
### прямые сообщения журнала в Stdout ### log4j.appender.stdout = org.apache.log4j.consoleappenderlog4j.appender.stdout.target = System.errlog4j.appender.stdout.layout = org.apache.log4j.patternlayoutlog4j.appender %c {1}: %l - %m %n ### Прямые сообщения для подачи mylog.log ### log4j.appender.file = org.apache.log4j.fileAppenderlog4j.appender.file.file = c/: mylog.loglog4j.appender.file.layout = org.apache.log4j.patternlayoutlog4j.appender.file.layout.conversion %c {1}: %l - %m %n ### Установить уровни журнала - для получения более многослойного изменения журнала «Информация» на «отладку» ### log4j.rootlogger = info, stdout4. Проверьте, успешно ли файл журнала развернута
пакет com.clj.demo1; import org.apache.log4j.logger; import org.junit.test;/** * Демо -журнал использование * @author Administrator * */public class demo1 {// Создать класс Log Private log = logger.getLogger (demo1.class); @Test public void run1 () {// Изменить информацию в атрибуте log4j.rootlogger на OFF, и log.info ("execute"); }}5. Определите интерфейс и реализуйте класс
интерфейс:
пакет com.clj.demo2; public interface userservice {public void sayshello ();}Класс реализации
пакет com.clj.demo2; открытый класс userserviceimpl реализует userservice {private String name; public String getName () {return name; } public void setName (string name) {this.name = name; } public void init () {System.out.println ("инициализировать .."); } public void sayshello () {System.out.println ("Hello Spring"+"/T"+name); } public void destory () {System.out.println ("Drouse .."); }}6. Определить файлы конфигурации специфичных для пружины
Определите имя ApplicationContext.xml, местоположение SRC, тот же каталог, что и файл журнала, импортируйте соответствующие ограничения и введите класс реализации в файл конфигурации. Просто начните с начала, используйте ограничения бобов
<? 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:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Use bean tag 1. The id value is unique (must write) 2. Note: class is the implementation classpath, not an interface (must write) 3. Initialization work before the core method is executed (select write) 4. Initialization work after the core method is executed (select write) --> <bean id="userService" init-method="init" destroy-method="destory"> <property name="name" value="Jaxiansen"></property> </bean> </beans>
7. тест
открытый класс demo1 { /*** Original Way* /@test public void run () {// Создание класса реализации userserviceimpl s = new userserviceimpl (); s.setname ("jaxiansen"); S.SayHello (); } / *** Старая заводская версия BeanFactory* Old Factory не будет создавать объекты файла конфигурации* / @test public void run2 () {beanfactory factory = new xmlbeanfactory (new classpathresource ("ApplicationContext.xml")); Userservice us = (userservice) factory.getbean ("userservice"); us.sayhello (); } /*** Используйте Spring Framework IOC Method* Создать сервер запуска в новой версии Factory для создания объекта файла конфигурации, и нет необходимости загружать фабрику при вызове* /@test public void run3 () {// Создать завод и загружать файл конфигурации ClassPathXMLAPPLICAT ClassPathxMlapplicationContext ("ApplicationContext.xml"); // Получить объект из заводского значения в файле конфигурации, здесь используется полиморфизм) userservice usi = (userservice) ac.getbean ("userservice"); // вызов метода объекта для выполнения usi.sayhello (); } /*** Метод Demo Discousit Method* Метод уничтожения бобов не будет выполнен автоматически*, если его автоматически называется автоматически в Scope = Singleton или в веб-контейнере, основная функция или тестовый корпус должны быть названы вручную (необходимо использовать метод Close () ClassPathxMlapplicationContext)* /@test public run4 () (// Создание факта и нагрузка на факт. (ClassPathxMlapplicationContext находится в SRC) ClassPathxMlApplicationContext ac = new ClassPathxMlapplicationContext ("ApplicationContext.xml"); // Получить объект из заводского значения в файле конфигурации, здесь используется полиморфизм) userservice usi = (userservice) ac.getbean ("userservice"); // вызов метода объекта для выполнения usi.sayhello (); // Класс реализации ApplicationContext предоставляет метод закрытия, и завод может быть закрыт, а метод Destory-Method может быть выполнен. }}Разница между старыми фабриками и новыми фабриками
* Разница между BeanFactory и ApplicationContext
* BeanFactory - BeanFactory берет ленивую загрузку, и боб будет инициализирован только тогда, когда вы получите в первый раз
* ApplicationContext - При загрузке ApplicationContext.xml будет создан конкретный экземпляр объекта Bean, и предоставляются некоторые другие функции.
* Доставка мероприятия
* Автоматическая сборка бобов
* Контекстные реализации различных слоев приложений
Резюме: Это самая основная демонстрация, которая настраивает класс реализации в файл конфигурации пружины. Каждый раз, когда сервер запускается, файл конфигурации будет загружен, тем самым создавая класс реализации.
1. Что такое инъекция зависимости?
Весна может эффективно организовать объекты уровней применения J2EE. Будь то объект действия управляющего уровня, объект обслуживания бизнес -слоя или объект DAO на упорном уровне, он может быть органично координирован и запускаться под руководством Spring. Spring организует объекты каждого слоя вместе свободно связанными. Объекты действия не должны заботиться о конкретной реализации объектов обслуживания, объекты службы не должны заботиться о конкретной реализации целевых объектов слоя, а вызовы для каждого объекта уровня полностью ориентированы на интерфейс. Когда система должна быть рефакторирована, количество переписывания кода будет значительно сокращено. Инъекция зависимостей делает бобы и бобы организованными в файлах конфигурации, а не в твердом кодировании. Понять инъекцию зависимости
Инъекция зависимости и инверсия контроля - та же концепция. Конкретное значение: когда роль (возможно, экземпляр Java, вызывающий абонент) нуждается в помощи другой роли (другой экземпляр Java, вызывающий абонент), в традиционном процессе программирования, абонент обычно создается вызывающим абонент. Но весной работа по созданию Callee больше не выполняется вызывающим абонент, поэтому она называется управляющей инверсией; Работа по созданию экземпляра Callee обычно выполняется с помощью пружинного контейнера, а затем вводится в вызывающего абонента, поэтому он также называется инъекцией зависимостей.
Будь то инъекция зависимости или контроль инверсии, это означает, что Spring принимает динамический и гибкий способ управления различными объектами. Конкретные реализации между объектами прозрачны друг другу.
2. Концепция МОК и Ди ди
* МОК - обратный контроль, управление инверсией, инвертировать право создания объекта на пружину! !
* Di - инъекция зависимости, впрыск зависимостей, когда структура пружины отвечает за создание объектов бобов, динамически вводя объекты зависимости в компонент бобов! !
3. Демо
Для переменных члена класса существует два общих метода инъекции.
Внедрение метода набора свойств и метода конструктора
Сначала продемонстрировать первый тип: внедрение метода набора свойств
1) Постоянный слой
пакет com.clj.demo3; public class customerdaoimpl {public void saip () {System.out.println («Я дао слоя настойчивости»); }}2) Бизнес -слой
Примечание. В настоящее время я хочу ввести уровень постоянства в бизнес -слой и передать право создать экземпляр слоя стойкости в рамку, условие состоит в том, что бизнес -слой должен предоставить атрибуты участника и установить методы уровня стойкости.
пакет com.clj.demo3;/** * Внедрение зависимости внедряет уровень DAO в уровень обслуживания * @Author Administrator * *//Public Class CustomerServiceImpl {// Предоставление участника Zodiac, предоставьте SET метод private CustomerDaiumpl CustomerDao; public void setcustomerdao (customerdaoimpl customerdao) {this.customerdao = customerdao; } public void save () {System.out.println ("Я - сервис ..."); // 1. Оригинальный метод // new CustomerDaoImpl (). Save (); //2.spring method method customerdao.save (); }}3) Конфигурация файла конфигурации
<!-Демонстрационная зависимость-> <bean id = "customerdao"/> <bean id = "customerservice"> <!-Inject dao в уровень обслуживания-> <name = "customerdao" ref = "customerdao"> </property> </bean>
4) тест
/** * Метод инъекции зависимости в зависимости от пружины * Внедрить слой DAO в сервисный уровень */@Test public void run2 () {// Создать завод, загрузить файл конфигурации и создавать Customer service, создавая таким образом CustomerDao context = new ClassPathxMlApplicationContext ("applicateContext.xml"); Customerserviceimpl csi = (customerserviceimpl) context.getbean ("customer service"); csi.save (); }Второй тип: внедрение метода строительства
1) класс POJO и предоставление методов конструктора
Пакет com.clj.demo4;/** * Метод демонстрации * @author Administrator * */public Carp Car1 {private String cname; частная двойная цена; public Car1 (String cname, двойная цена) {super (); this.cname = cname; this.price = цена; } @Override public String toString () {return "car1 [cname =" + cname + ", price =" + price + "]"; }}2) Конфигурация файла конфигурации
<!-Продемонстрировать метод внедрения метода строительства-> <Bean id = "car1"> <!-метод записи 1 <constructor-arg name = "cname" value = "bmw"/> <constructor-arg name = "price" value = "400000"/>-> <!-Method 2-> <constructor-arg index = "0" value = "bmwor"/> <! index = "1" value = "400000"/> </bean>
3) тест
@Test public void run1 () {ApplicationContext ac = new ClassPathxMlapplicationContext ("ApplicationContext.xml"); CAR1 CAR = (CAR1) AC.GETBEAN ("CAR1"); System.out.println (CAR); }Расширение: построение метода вводит один объект в другой
1) POJO Class: Цель: введите автомобиль в приведенном выше столбце в людей и сделайте его одним из атрибутов. В этом классе должны быть предоставлены атрибуты элемента автомобиля, и должны быть предоставлены параметризованные методы строительства.
пакет com.clj.demo4; public class person {private String name; Частный автомобиль1 CAR1; Public Perform (название строки, Car1 Car1) {super (); this.name = name; this.car1 = car1; } @Override public String toString () {return "person [name =" + name + ", car1 =" + car1 + "]"; }}2) Файл конфигурации
<!-Constructor-Arg name = "name" value = "jaxiansen"/> <constructor-arg name = "car1" ref = "car1"/> </bean>
4. Как ввести массив сбора
1) Определите класс POJO
пакет com.clj.demo4; import java.util.arrays; import java.util.list; import java.util.map; import java.util.properties; import java.util.set;/** * Демонстрируйте способ установить инъекцию * @author Administrator * */Public Class {Private String [] ARRRS; частный список <string> list; Private SET <String> sets; Приватная карта <строка, строка> map; Private Properties Pro; public void setPro (Properties pro) {this.pro = pro; } public void setsets (set <string> sets) {this.sets = sets; } public void setMap (map <string, string> map) {this.map = map; } public void SetList (список <string> list) {this.list = list; } public void setarrrs (string [] arrrs) {this.arrs = arrrs; } @Override public String toString () {return "user [arrs =" + arrays.tostring (arrs) + ", list =" + list + ", sets =" + sets + ", map =" + map + ", pro =" + pro + "]"; }}2) Файл конфигурации
<!-Набор инъекций-> <bean id = "user"> <!-Array-> <name = "arrs"> <list> <dalue> number1 </value> <duld> number2 </value> <dalue> number3 </value> </list> </properation> <!-Список набор-> name = "list"> <dist> <ditue> jin zaizong> </property> <!-Установите набор-> <name = "sets"> <Set> <date> <value> хаха </value> <dall> хаха </value> </set> </property> <!-Карта набор-> <и имя свойства = "map"> <map> <inpit key = "aa" value = "Rainbow"/> <inpit key = "bb" value = "hellowvenus"/> </> </> </> </> </map> </> </> </map> </> </> </> </map> </> </> </> </> </> </> </> </карта> </> </map. name = "pro"> <props> <prop key = "username"> root </prop> <prop key = "password"> 123 </prop> </props> </property> </bean>
3) тест
/ *** Коллекция инъекций теста*/ @test public void run3 () {ApplicationContext ac = new ClassPathxMlapplicationContext ("ApplicationContext.xml"); Пользователь пользователь = (пользователь) ac.getbean ("user"); System.out.println (пользователь); }5. Как развиваться в модулях
Добавьте тег <import> в основной файл конфигурации (предположим, что файл configuration file context2.xml определяется в пакете com.clj.test)
<!-Представление других файлов конфигурации по разработке модуля-> <import resource = "com/clj/test/applicationcontext2.xml"/>
1. Начало работы
1). Import Jar Package
В дополнение к предыдущим 6 пакетам, вам также нужен пакет Spring-Aop, чтобы воспроизводить аннотацию.
2). Уровень постоянства и уровень реализации (интерфейсы здесь игнорируются)
Постоянный слой
пакет com.clj.demo1; import org.springframework.context.annotation.scope; import org.springframework.stereotype.component; импорт org.springframework.sterotype.Repository;/** * Public Class Managemat @Override public void said () {System.out.println ("Сохранить клиент .."); }}Бизнес -слой
пакет com.clj.demo1; import javax.annotation.postconstruct; import org.springframework.beans.factory.annotation.autowired; импорт org.springframework.beans.factory.annotation.valifier; import org.spramework.beans.factory.annotation.value; org.springframework.stereotype.component; открытый класс пользователи userserviceimpl реализует userservice {@override public void sayshello () {system.out.println ("hello spring"); }}3). Определите файл конфигурации
В настоящее время ограничения должны добавлять контекстные ограничения и добавить сканирование компонентов
<? 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.spramework.org/schema/beans/springbeans.s.xspringbeansbeans.s.xspringbeans.s.xspringbeans.s.xspringbeans/springbeans.s.xspring.sspring.sspring.s.spers.springbeans/spring-beans.s.spersbemans./www.spramework. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-Определения Beans здесь-> <!-Откройте аннотацию: base-package = "com.clj.demo1"/> </beans>
4) Добавить аннотации в класс реализации
/*** Аннотация компонента, которая может использоваться для обозначения текущего класса*, аналогичного <bean id = "userservice">* Значение означает предоставление псевдонима для класса*/@component (value = "userservice") общедоступный класс userserviceimpl реализует userservice {// Опущено}5) Напишите тесты
/ *** Метод аннотации*/ @test public void run2 () {ApplicationContext ac = new classpathxmlapplicationContext ("ApplicationContext.xml"); Userservice us = (userservice) ac.getbean ("userservice"); us.sayhello (); }2. Об общих атрибутах управления бобами
1. @component: компонент. (действовал в классе) самая примитивная аннотация, можно написать это для всех классов, которые нуждаются в аннотации, это общее
2. Три производных аннотации @Component представлены весной: (функции в настоящее время согласуются)
* @Controller - работает на веб -слое
* @Service - действует на бизнес -уровне
* @Repository - действует на упорном слое
* Примечание. Эти три аннотации предназначены для того, чтобы прояснить цель самого класса аннотаций, а пружина улучшит его в последующих версиях.
3. Аннотации для инъекции атрибутов (примечание: при использовании впрыска аннотации вам не нужно предоставлять заданный метод)
* Если это нормальный тип инъекции, вы можете использовать аннотацию значения
* @Value - для инъекции нормальных типов
* Если тип инъекционного объекта, используйте следующую аннотацию
* @Autowired - по умолчанию тип автоматически собирается по типу, и он не имеет ничего общего с именем класса вводящего класса.
* Если вы хотите вводить по имени
* @Qualifier - принудительное использование впрыска имени должно использоваться с Autowailired, укажите имя класса и связано с именем введенного класса
* @Resource - эквивалент @autowired и @qualifier
* Подчеркните: аннотации, предоставленные Java
* Атрибут использует атрибут имени
4. аннотация масштаба бобов
* Аннотирован как @scope (value = "prototype"), который используется в классе. Значения следующие:
* Singleton - Singleton, значение по умолчанию
* Прототип - несколько случаев
5. Конфигурация жизненного цикла бобов (понимать)
* Аннотация следующая:
* @Postconstruct-эквивалент init-method
* @Predestroy-эквивалент уничтожению-метод
1. Демонстрировать аннотацию объекта атрибута
Условие: инъекционные атрибуты (имя) и объект (userDaoImpl) в бизнес -уровень путем сканирования.
1) Откройте слой настойчивости, чтобы сканировать аннотацию
//@component (value = "userDao") Universal Class Annotation@Repository (value = "ud") открытый класс userDaoImpl реализует userdao {@Override public void said () {System.out.println ("Сохранить клиент .."); }}2) Бизнес -уровень предоставляет аннотации для атрибутов и объектов
пакет com.clj.demo1; import javax.annotation.postconstruct; import org.springframework.beans.factory.annotation.autowired; импорт org.springframework.beans.factory.annotation.valifier; import org.spramework.beans.factory.annotation.value; org.springframework.stereotype.component;/** * Аннотация компонента может использоваться для обозначения текущего класса *, аналогичного <bean id = "userservice"> * Значение означает предоставление псевдонима в классе * /// @ @acmope (value = "grototype") несколько столбцов (Singletype - это один столбец) @component (value = "userserseerserserseers atomerserseers aterviceserserseers atemporeersersemersemessersempersemessersempersemperes atemberseers atemporeService. // Аннотация атрибута: она эквивалентна инъекции указанной строки в атрибут имени. Метод SETNAME может быть опущен без написания @Value (value = "jaxiansen") частное название строки; /** * Метод введения ссылки 1: AutoWired () * Метод инъекции эталонного введения 2: AutoWireD () + Квалификатор * Метод инъекции ссылки 3: @Resource (name = "userDao") Метод Java, идентифицировать внедрение по имени */// Autowailired () автоматически собирается и вводя @Qualifier (value = "ud") // Инъекция по имени он должен использоваться с AutoWovired. Оба могут указать класс private userdao userdao; // Обратите внимание, что значение в квалификаторе - это имя аннотации в верхней части имени класса userDaoImpl, или вы можете указать идентификационное имя боба в файле конфигурации/*public void setName (String name) {this.name = name; }*/ @Override public void sayshello () {System.out.println ("Привет пружина"+name); userdao.save (); } // @postconstruct Tag Аннотация для инициализации в жизненном цикле действия @postconstruct public init () {System.out.println ("инициализировать ..."); }}3) Файл конфигурации должен быть включен только для сканирования всех файлов конфигурации
<? 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.spramework.org/schema/beans/springbeans.s.xspringbeansbeans.s.xspringbeans.s.xspringbeans.s.xspringbeans/springbeans.s.xspring.sspring.sspring.s.spers.springbeans/spring-beans.s.spersbemans./www.spramework. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-Определения Beans здесь-> <!-Откройте аннотацию: base-package = "com.clj.demo1"/> </beans>
Примечание. Что касается коллекций, рекомендуется использовать файлы конфигурации
2. Spring Framework интегрирует тестирование модуля JUNIT
1) Добавить необходимый пакет зависимостей Spring-test.jar
Примечание: Myeclipes поставляется со своей собственной средой JUNIT, но иногда из -за проблем с версией может потребоваться новая среда JUNIT. Здесь я загрузил новый пакет JUNT-4.9 онлайн. Если Myeclipes новее, вам не нужно рассматривать это.
2) Напишите тестовый класс и добавьте соответствующие аннотации
@RunWith и @ContextConfiguration (это используется для загрузки файла конфигурации, поскольку путь по умолчанию от WebRoot является каталогом первого уровня, плюс это для определения того, что SRC является каталогом первого уровня)
пакет com.clj.demo2; import javax.annotation.resource; import org.junit.test; import org.junit.runner.runwith; импорт org.springframework.test.context.contextConfiguration; импорт org.spramework.test.context.junit4.springjunit; com.clj.demo1.userservice; @runwith (springjunit4classrunner.class) @ContextConfiguration ("classPath: ApplicationContext.xml") открытый класс demo2 {@Resource (name = "userService") private userService userService; @Test public void run1 () {userservice.sayhello (); }}6. AOP Spring Framework
1. Что такое AOP
* В индустрии программного обеспечения AOP является аббревиатурой ориентированного на аспект программирования, значение: программирование аспектов, функциональная модульность
* AOP - это парадигма программирования, связанная с категорией мягкой работы, направляя разработчиков, как организовать программные структуры
* AOP был впервые предложен организацией AOP Alliance и разработал набор норм. Весна ввела идеи AOP в рамку и должна соблюдать спецификации AOP Alliance.
* Технология для достижения единого обслуживания программ
* AOP - это продолжение ООП, горячая тема в разработке программного обеспечения, важная часть пружинной структуры и производная парадигма функционального программирования.
* Используя AOP, могут быть изолированы различные части бизнес -логики, тем самым уменьшая связь между частями бизнес -логики, улучшив повторное использование программы и повышение эффективности развития.
AOP принимает механизм горизонтального извлечения, заменяя повторяющийся код традиционной системы вертикального наследования (мониторинг производительности, управление транзакциями, проверка безопасности, кэширование)
2. Зачем изучать AOP
* Программа может быть улучшена без изменения исходного кода! ! (Создайте прокси для фиксированного метода. Прежде чем получить доступ к методу, сначала введите прокси. В прокси вы можете написать больше функций, чтобы сделать метод более мощным и улучшить программу)
AOP: ориентированное программирование, модульное все, каждый модуль является относительно независимым, модули могут быть переданы (то же самое), а различные особенно настроены. Используйте это вместо традиционного вертикального программирования для улучшения использования программы повторного использования
3. Реализация AOP (принцип реализации)
Реализация AOP включает в себя два прокси -метода <1> для реализации интерфейсов класса: используйте динамический прокси JDK <2> Не реализованные интерфейсы класса: используйте динамический прокси CGLIB
1. Реализация динамического прокси JDK
1) Определите класс реализации интерфейса интерфейса устойчивости
пакет com.clj.demo3; public interface userdao {public void said (); public void update ();} пакет com.clj.demo3; открытый класс userdaoimpl реализует userdao {@override public void said () {system.out.println ("Сохранить пользователь"); } @Override public void update () {System.out.println ("Modify User"); }}2) Определите класс инструментов динамического прокси -инструмента JDK
Этот класс инструментов добавляет некоторые функции при выполнении метода сохранения уровня настойчивости, и в разработке необходимо улучшить определенный метод без изменения исходного кода
Пакет com.clj.demo3; импорт java.lang.reflect.invocationHandler; импорт java.lang.reflect.method; import java.lang.reflect.proxy;/** * Создание объектов Proxy в jdk (демонстрировать принципы aop) * @author Administrator */public class myproxitil Userdao dao) {// Использовать класс прокси для генерации Proxy Objects userDao proxy = (userdao) proxy.newproxyinstance (dao.getClass (). GetClassloader (), dao.getClass (). Invoke (Proxy Object, метод метода, Object [] args) бросает Throkable {// Прокси представляет текущий метод прокси //, выполняемый текущим объектом // args, инкапсулированными параметрами // позволить классу сохранить или обновлять метод обычно, если («Сохранить» method.invoke (dao, args); вернуть прокси; }}3) тест
пакет com.clj.demo3; import org.junit.test; public class demo1 {@test public void run1 () {// Получить целевой объект userdao dao = new userdaoimpl (); dao.save (); dao.update (); System.out.println ("===================================================================== ====================================================================================== Используйте класс инструментов, чтобы получить Proxy Object UserDao Proxy = myProxyutils.getProxy (dao);2. Внедрение технологии CGLIB
1) Определить слой постоянства, в настоящее время нет интерфейса.
пакет com.clj.demo4; public class bookdaoimpl {public void said () {System.out.println ("Сохранить книгу"); } public void Update () {System.out.println ("Модифицировать книгу"); }}2) Написать классы инструментов
пакет com.clj.demo4; импортировать java.lang.reflect.method; импорт org.springframework.cglib.proxy.enhancer; импорт org.springframework.cglib.proxy.methodinterceptor; import org.spramework.clib.proxy.methodproxy; Метод прокси * @author Administrator * */public Class MyCglibitils {/** * Сгенерировать объект прокси с использованием метода CGlib * @return */public static bookdaoimpl getProxy () {Enhancer Enhancer = new Enhancer (); // Установить родительский класс Enhancer.setSuperClass (bookdaoimpl.class); // Установить функцию обратного вызова Enhancer.setCallback (new MethodInterceptor () {@Override Public Object Intercept (объект obj, метод метода, объект [] objs, методпрокси -метод Прокси) бросает throwable {if (method.getName (). Equals ("save")) {system.out.println ("i savaled") } return methodproxy.invokesuper (obj, objs); // - это метод, выполненный}}); // генерировать прокси -объект BookDaoImpl Proxy = (bookDaoImpl) Enhancer.Create (); вернуть прокси; }}3) Записать тестовые классы
пакет com.clj.demo4; import org.junit.test; public class demo1 {@test public void run1 () {// целевой объект bookdaoimpl dao = new bookdaoimpl (); dao.save (); dao.update (); System.out.println ("================================================================================================3. Разработка AOP Spring на основе AspectJ (метод файла конфигурации)
1) Развернуть среду и импортировать соответствующий пакет JAR
2) Создать файлы конфигурации и ввести ограничения AOP
<Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-insstance" xmlns: aop = "http://www.spramemema" xmlns: aop = "http://www.spramemema stance". xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop./www.springframework.org/schema/aop:/www.springframework.org/schema/aop.spramewor http://www.springframework.org/schema/aop/spring-aop.xsd ">
3) Создать интерфейсы и внедрять классы
пакет com.clj.demo5; public interface customerdao {public void said (); public void update ();} пакет com.clj.demo5;/** * Используйте файл конфигурации для интерпретации AOP * @Author Administrator * */Public Class CustomerDaoImpl реализует CustomerDao {@Override public void said () {// Симулировать Exception // int a = 10/0; System.out.println («Сохранить клиента»); } @Override public void update () {// todo автоматическое сгенерированное метод System.out.println («Обновление клиента»); }}4) Определите класс фасета
Пакет com.clj.demo5; import org.aspectj.lang.proudecingjoinpoint;/** * Класс Facet: точка входа + уведомление * @author Administrator * */public class myAspectxml {/** * Уведомление (конкретное улучшение) */public Void Log () {System.out.println ("log log"); } / ** * Метод выполняется успешно или исключения будут выполнены * / public void After () {System.out.println ("Окончательное уведомление"); } /*** После выполнения метода выполняется уведомление о сообщении. Если в программе возникает исключение, уведомление POST не будет выполнено */ public void AfterReturn () {System.out.println ("post уведомление"); } / ** * После выполнения метода, если есть исключение, уведомление об исключении будет выполнено * / public void Afterthroing () {System.out.println ("Уведомление об исключении"); } /*** Уведомление о окружении: уведомление делается до и после выполнения метода. * По умолчанию метод целевого объекта не может быть выполнен, и целевой объект должен быть выполнен вручную */ public void вокруг (ходатайство Joinpoint joinpoint) {System.out.println ("Уведомление об wrap 1"); // вручную позволить методу целевого объекта выполнить try {joinpoint.proceed (); } catch (throwable e) {// todo автоматически сгенерированный блок e.printstacktrace (); } System.out.println ("Уведомление об обложке 2"); }}5) Введите классы реализации и классы аспектов
<? 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: aop = "http://www.springframework.org/schema/aop" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.spramework.org/schema/beans/spring-beans.xspring-beans.spring-beansbembemabema/beansbemans. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "> <!-Определения Beans здесь-> <! id="myAspectXml"/> <!-- Configure the section class --> <bean id="myAspectXml"/> <!-- Configure the section class: entry point + notification (type) --> <aop:aspect ref="myAspectXml"> <!-- Configure the pre-notification, and the enhancement method will be executed before the save method is executed --> <!-- Point cutting expression: execution(public void com.clj.demo5.CustomerDaoImpl.save()) --> <!-- Point cutting expression: 1.execution() is fixed, must be written 2.public can be omitted and not written 3. The return value must be written, strictly based on the point cutting method, otherwise the enhancement method will not be executed, and it can be replaced by * to represent any return value 4. The package name must be written, and it can be replaced by * (such as: *..* (default all packages); com.clj.*) 5. The class name must be written. You can partially use * (such as *DaoImpl means a persistent layer implementation class ending with 'DaoImpl'), but it is not recommended to use * instead of the entire class name 6. The method must be written. You can partially use * (such as save* means a method starting with 'save'), but it is not recommended to use * instead of the entire class name 7. The method parameters are determined according to the actual method, and you can use '..' to indicate that there are 0 or more parameters --> <!-- <aop:before method="log" pointcut="execution(public void com.clj.*.CustomerDaoImpl.save(..))"/> --> <aop:before method="log" pointcut="execution(* *..*.*DaoImpl.save*(..))"/> </aop:aspect> </aop:config></beans>
6)测试
package com.clj.demo5;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo1 { @Resource(name="customerDao") private CustomerDao customerDao; @Test public void run(){ customerDao.save(); customerDao.update(); }}扩展:切面类升级
<? 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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here --> <bean id="myAspectXml"/> <aop:config> <aop:aspect ref="myAspectXml"> <!-- Configure final notification<aop:after method="after" pointcut="execution(* *..*.*DaoImpl.save*(..))"/>-- Configure post-notification<aop:after-returning method="afterReturn" pointcut="execution(* *..*.*DaoImpl.save*(..))"/>--> <!-- Configuration exception notification<aop:after-throwing method="afterThrowing" pointcut="execution(* *..*.*.DaoImpl.save*(..))"/>--> <aop:around method="around" pointcut="execution(* *..*.*.DaoImpl.update*(..))"/> </aop:aspect> </aop:config></beans>
4、Spring框架AOP之注解方式
1)创建接口和实现类
package com.clj.demo1;public interface CustomerDao { public void save(); public void update();} package com.clj.demo1;public class CustomerDaoImpl implements CustomerDao{ @Override public void save() { // TODO Auto-generated method stub System.out.println("Save customer.."); } @Override public void update() { // TODO Auto-generated method stub System.out.println("Update customer"); }}2)定义切面类
package com.clj.demo1;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;/** * 注解方式的切面类* @Aspect表示定义为切面类*/@Aspectpublic class MyAspectAnno { //通知类型:@Before前置通知(切入点的表达式) @Before(value="execution(public * com.clj.demo1.CustomerDaoImpl.save())") public void log(){ System.out.println("记录日志。。"); } //引入切入点@After(value="MyAspectAnno.fun()") public void after(){ System.out.println("执行之后"); } @Around(value="MyAspectAnno.fun()") public void around(ProceedingJoinPoint joinPoint){ System.out.println("环绕通知1"); try { //让目标对象执行joinPoint.proceed(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("环绕通知2"); } //自定义切入点@Pointcut(value="execution(public * com.clj.demo1.CustomerDaoImpl.save())") public void fun(){ }}3)配置切面类和实现类,并开启自动代理
<? 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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- Turn on the automatic annotation proxy --> <aop:aspectj-autoproxy/> <!-- Configure the target object --> <bean id="customerDao"/> <!-- Configure the facet class --> <bean id="myAspectAnno"/></beans>
spring提供了JDBC模板:JdbcTemplate类
1.快速搭建
1)部署环境
这里在原有的jar包基础上,还要添加关乎jdbc的jar包,这里使用的是mysql驱动
2)配置内置连接池,将连接数据库程序交给框架管理,并配置Jdbc模板类
<? 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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- Configure the connection pool first (built-in) --> <bean id="dataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!-- Configure the template class for JDBC --> <bean id="jdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean></beans>
3)测试
package com.clj.demo2;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;import javax.annotation.Resource;import org.apache.commons.dbcp.BasicDataSource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.cglib.beans.BeanMap;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/** * 测试JDBC的模板类,使用IOC的方式* @author Administrator * */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo2 { @Resource(name="jdbcTemplate") private JdbcTemplate jdbcTemplate; /** * 插入*/ @Test public void run1(){ String sql="insert into t_account values(null,?,?)"; jdbcTemplate.update(sql,"李钇林",10000); } /** * 更新*/ @Test public void run2(){ String sql="update t_account set name=? where id=?"; jdbcTemplate.update(sql,"李钇林",1); } /** * 删除*/ @Test public void run3(){ String sql="delete from t_account where id=?"; jdbcTemplate.update(sql,4); } /** * 测试查询,通过主键来查询一条记录*/ @Test public void run4(){ String sql="select * from t_account where id=?"; Account ac=jdbcTemplate.queryForObject(sql, new BeanMapper(),1); System.out.println(ac); } /** * 查询所有*/ @Test public void run5(){ String sql="select * from t_account"; List<Account> ac=jdbcTemplate.query(sql,new BeanMapper()); System.out.println(ac); }}/** * 定义内部类(手动封装数据(一行一行封装数据,用于查询所有) * @author Administrator * */class BeanMapper implements RowMapper<Account>{ @Override public Account mapRow(ResultSet rs, int rowNum) throws SQLException { Account ac=new Account(); ac.setId(rs.getInt("id")); ac.setName(rs.getString("name")); ac.setMoney(rs.getDouble("money")); return ac; } }2、配置开源连接池
一般现在企业都是用一些主流的连接池,如c3p0和dbcp
首先配置dbcp
1)导入dbcp依赖jar包
2)编写配置文件
<!-- 配置DBCP开源连接池--> <bean id="dataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean>
将模板类中引入的内置类datasource改为开源连接池的
3)编写测试类
配置c3p0
1)导入c3p0依赖jar包
2)配置c3p0
<!-- 配置C3P0开源连接池--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean>
将模板类中引入的内置类datasource改为开源连接池的
3)编写测试类
1、什么是事务
数据库事务(Database Transaction) ,是指作为单个逻辑工作单元执行的一系列操作,要么完全地执行,要么完全地不执行。 事务处理可以确保除非事务性单元内的所有操作都成功完成,否则不会永久更新面向数据的资源。通过将一组相关操作组合为一个要么全部成功要么全部失败的单元,可以简化错误恢复并使应用程序更加可靠。一个逻辑工作单元要成为事务,必须满足所谓的ACID(原子性、一致性、隔离性和持久性)属性。事务是数据库运行中的逻辑工作单位,由DBMS中的事务管理子系统负责事务的处理。
2、怎么解决事务安全性问题
读问题解决,设置数据库隔离级别;写问题解决可以使用悲观锁和乐观锁的方式解决
3、快速开发
方式一:调用模板类,将模板注入持久层
1)编写相对应的持久层和也外层,这里省略接口
package com.clj.demo3;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.support.JdbcDaoSupport;public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{ // Method 1: Inject the jdbc template class into the configuration file and write the template class private in the persistence layer JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void outMoney(String out, double money) { String sql="update t_account set money=money-? where name=?"; jdbcTemplate().update(sql,money,out); } public void inMoney(String in, double money) { String sql="update t_account set money=money+? where name=?"; jdbcTemplate().update(sql,money,in); }} package com.clj.demo4;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;public class AccountServiceImpl implements AccountService{ //It uses configuration file injection method, and the set method must be provided private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void pay(String out, String in, double money) { // TODO Auto-generated method stub accountDao.outMoney(out, money); int a=10/0; accountDao.inMoney(in, money); }}2)配置相对应的配置文件
<? 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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- Configuring the C3P0 open source connection pool--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean><!-- Configure the template class of JDBC --> <bean id="jdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean><!-- Configure the business layer and persistence layer --> <bean id="accountService"> <property name="accountDao" ref="accountDao"/> </bean><bean id="accountDao"> <!-- Inject the template class --> <property name="jdbcTemplate" ref="jdbcTemplate"/> <property name="dataSource" ref="dataSource"/> </bean></beans>
3)测试类
package com.clj.demo3;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo1 { @Resource(name="accountService") private AccountService accountService; @Test public void Demo1(){ //Call the payment method accountService.pay("Jia Xiansen","Li Yilin",100); }}方式二:持久层继承JdbcDaoSupport接口,此接口封装了模板类jdbcTemplate
1)编写配置文件
<? 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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- Configure C3P0 open source connection pool--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- Configure the business layer and persistence layer--> <bean id="accountService"> <property name="accountDao" ref="accountDao"/> </bean> <bean id="accountDao"> <property name="dataSource" ref="dataSource"/> </bean></beans>
2)更改持久层
package com.clj.demo3;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.support.JdbcDaoSupport;public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{ //Method 1: Inject the jdbc template class into the configuration file and write the template class directly in the persistence layer// private JdbcTemplate jdbcTemplate;// public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {// this.jdbcTemplate = jdbcTemplate;// } // Method 2: The persistence layer inherits JdbcDaoSupport, which encloses the template class. The persistence layer of the configuration file does not need to inject the template class, nor does it need to configure the template class public void outMoney(String out, double money) { //jdbcTemplate.update(psc); String sql="update t_account set money=money-? where name=?"; this.getJdbcTemplate().update(sql,money,out); } public void inMoney(String in, double money) { String sql="update t_account set money=money+? where name=?"; this.getJdbcTemplate().update(sql,money,in); }}3)更改业务层
package com.clj.demo4;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;public class AccountServiceImpl implements AccountService{ //It uses configuration file injection method, and the set method must be provided private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void pay(String out, String in, double money) { // TODO Auto-generated method stub accountDao.outMoney(out, money); int a=10/0; accountDao.inMoney(in, money); }}4)测试类和上述一样
4、spring事务管理
In order to simplify transaction management code, Spring provides a template class TransactionTemplate, which can be manually programmed to manage transactions. You only need to use this template class! !
1、手动编程方式事务(了解原理)
1)快速部署,搭建配置文件,配置事务管理和事务管理模板,并在持久层注入事务管理模板
配置事务管理器
<!-- 配置平台事务管理器--> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean>
配置事务管理模板
<bean id="transactionTemplate"> <property name="transactionManager" ref="transactionManager"/></bean>
将管理模板注入业务层
<bean id="accountService"> <property name="accountDao" ref="accountDao"/> <property name="transactionTemplate" ref="transactionTemplate"/></bean>
全部代码:
<? 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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- Configure C3P0 open source connection pool--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- Configure the business layer and persistence layer--> <bean id="accountService"> <property name="accountDao" ref="accountDao"/> <property name="transactionTemplate" ref="transactionTemplate"/> </bean> <bean id="accountDao"> <property name="dataSource" ref="dataSource"/> </bean> <!-- Configure the platform transaction manager--> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- Configure the platform transaction manager--> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- Manual encoding method, providing a template class, using this class to manage transactions is simpler --> <bean id="transactionTemplate"> <property name="transactionManager" ref="transactionManager"/> </bean></beans>
2)在业务层使用模板事务管理
package com.clj.demo3;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;public class AccountServiceImpl implements AccountService{ //Usage configuration file injection method, set method must be provided private AccountDao accountDao; //Inject transaction template class private TransactionTemplate transactionTemplate; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } public void setTransactionTemplate(TransactionTemplate transactionTemplate) { this.transactionTemplate = transactionTemplate; } /** * Method of transfer*/ public void pay(final String out,final String in, final double money) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { //The execution of the transaction, if there is no problem, submit, if Chu Xiang is exception, roll back protected void doInTransactionWithoutResult(TransactionStatus arg0) { // TODO Auto-generated method stub accountDao.outMoney(out, money); int a=10/0; accountDao.inMoney(in, money); } }); }}3)测试类和上一致
package com.clj.demo4;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext2.xml")public class Demo2 { @Resource(name="accountService") private AccountService accountService; @Test public void Demo1(){ //Call the payment method accountService.pay("Jia Xiansen","Li Yilin",100); }}申明式事务有两种方式:基于AspectJ的XML方式;基于AspectJ的注解方式
1、XML方式
1)配置配置文件
需要配置平台事务管理
<!-- 配置C3P0开源连接池--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- 配置平台事务管理器--> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean>
配置事务增强
<tx:advice id="myAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 给方法设置数据库属性(隔离级别,传播行为) --> <!--propagation事务隔离级别:一般采用默认形式:tx:method可以设置多个--> <tx:method name="pay" propagation="REQUIRED"/> </tx:attributes> </tx:advice>
aop切面类
<aop:config> <!-- aop:advisor,是spring框架提供的通知--> <aop:advisor advice-ref="myAdvice" pointcut="execution(public * com.clj.demo4.AccountServiceImpl.pay(..))"/> </aop:config>
全部代码
<? 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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- Configure C3P0 open source connection pool--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- Configure platform transaction manager --> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- Declaration transaction (using XML file method) --> <!-- Configure notifications first-> <tx:advice id="myAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- Set database attributes for the method (isolation level, propagation behavior) --> <!-- Propagation transaction isolation level: generally use the default form: tx:method can set multiple --> <tx:method name="pay" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- Configure AOP: If it is an AOP written by yourself, use aop:aspect configuration, use notifications provided by Spring framework--> <aop:config> <!-- aop:advisor, is notifications provided by spring framework--> <aop:advisor advice-ref="myAdvice" pointcut="execution(public * com.clj.demo4.AccountServiceImpl.pay(..))"/> </aop:config> <!-- Configure business layer and persistence layer--> <bean id="accountService"> <property name="accountDao" ref="accountDao"/> </bean> <bean id="accountDao"> <property name="dataSource" ref="dataSource"/> </bean></beans>
2)编写持久层和业务层(省略接口)
package com.clj.demo5;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.support.JdbcDaoSupport;public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{ //Method 1: Inject the jdbc template class into the configuration file and write the template class directly in the persistence layer// private JdbcTemplate jdbcTemplate;// public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {// this.jdbcTemplate = jdbcTemplate;// } // Method 2: The persistence layer inherits JdbcDaoSupport, which encloses the template class. The persistence layer of the configuration file does not need to inject the template class, nor does it need to configure the template class public void outMoney(String out, double money) { //jdbcTemplate.update(psc); String sql="update t_account set money=money-? where name=?"; this.getJdbcTemplate().update(sql,money,out); } public void inMoney(String in, double money) { String sql="update t_account set money=money+? where name=?"; this.getJdbcTemplate().update(sql,money,in); }} package com.clj.demo5;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.annotation.Transactional;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;public class AccountServiceImpl implements AccountService{ //It uses configuration file injection method, and the set method must be provided private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void pay(String out, String in, double money) { // TODO Auto-generated method stub accountDao.outMoney(out, money); int a=10/0; accountDao.inMoney(in, money); }}3)测试类
package com.clj.demo4;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext2.xml")public class Demo2 { @Resource(name="accountService") private AccountService accountService; @Test public void Demo1(){ //Call the payment method accountService.pay("Jia Xiansen","Li Yilin",100); }}2、注解方式
1)配置配置文件
配置事务管理
<bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean>
开启注释事务
<!-- 开启事务的注解--> <tx:annotation-driven transaction-manager="transactionManager"/>
全部代码
<? 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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- Configure C3P0 open source connection pool--> <bean id="dataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- Configure platform transaction manager--> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- Open transaction annotation-driven transaction-manager="transactionManager"/> <!-- Configure business layer and persistence layer--> <bean id="accountService"> <property name="accountDao" ref="accountDao"/> </bean> <bean id="accountDao"> <property name="dataSource" ref="dataSource"/> </bean></beans>
2)业务层增加@Transactional
package com.clj.demo5;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.annotation.Transactional;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;//Add this annotation in the current class means that all the current class has transactions @Transactionalpublic class AccountServiceImpl implements AccountService{ //Using configuration file injection method, the set method must be provided private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void pay(String out, String in, double money) { // TODO Auto-generated method stub accountDao.outMoney(out, money); int a=10/0; accountDao.inMoney(in, money); }}3)持久层不变
package com.clj.demo5;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.support.JdbcDaoSupport;public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{ //Method 1: Inject the jdbc template class into the configuration file and write the template class directly in the persistence layer// private JdbcTemplate jdbcTemplate;// public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {// this.jdbcTemplate = jdbcTemplate;// } // Method 2: The persistence layer inherits JdbcDaoSupport, which encloses the template class. The persistence layer of the configuration file does not need to inject the template class, nor does it need to configure the template class public void outMoney(String out, double money) { //jdbcTemplate.update(psc); String sql="update t_account set money=money-? where name=?"; this.getJdbcTemplate().update(sql,money,out); } public void inMoney(String in, double money) { String sql="update t_account set money=money+? where name=?"; this.getJdbcTemplate().update(sql,money,in); }}4)测试类
package com.clj.demo5;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext3.xml")public class Demo3 { @Resource(name="accountService") private AccountService accountService; @Test public void Demo1(){ //Call the payment method accountService.pay("Jia Xiansen","Li Yilin",100); }}Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.