• Spring Dmitry Dvoynov
1 • План • Core Container • Data Access/Integration • Web
• Core Container
3 • Spring Спринг –коллекция мощных и гибких инструментов упрощающих разработку приложений
• public class Transfer. Service { public void transfer(double amount, String from. Id, String to. Id) { // Transfer. Service зависит от account. Dao // где должен быть объявлен account. Dao? Account from = account. Dao. find. By. Id(from. Id); Account to = aaccount. Dao. find. By. Id(from. Id); from. debit(amount); to. credit(amount); account. Dao. save(from); account. Dao. save(to); } }
public class Transfer. Service { • public void transfer(double amount, String from. Id, String to. Id) { Account. Dao account. Dao = new Jdbc. Account. Dao(. . . ); // создание внутри метода? //Transfer. Service управляет созданием accounts //Transfer. Service знает о реализации Jdbc. Account. Dao //Transfer. Service сложно протестировать Account from = account. Dao. find. By. Id(from. Id); Account to = account. Dao. find. By. Id(from. Id); from. debit(amount); to. credit(amount); account. Dao. save(from); account. Dao. save(to); } }
public class Transfer. Service { • private final Account. Dao account. Dao; public Transfer. Service(Account. Dao account. Dao) { this. account. Dao = account. Dao; } public void transfer(double amount, String from. Id, String to. Id) { //Реализация метода осталась простой, хорошо тестируемой Account from = account. Dao. find. By. Id(from. Id); Account to = account. Dao. find. By. Id(from. Id); from. debit(amount); to. credit(amount); account. Dao. save(from); account. Dao. save(to); } }
7 • Io. C и DI • Inversion of Control – управление зависимостями находится не внутри объекта , а – снаружи • Dependency Injection – внедрение зависимостей в объект
8 • Основы Spring • Bean – объект, который создается и управляется контейнером • Container – приложение, отвечающее за создание и конфигурирование бинов • Configuration metadata – описание конфигурации контейнера
9 • Spring Bean public class Default. Transfer. Service implements Transfer. Service { private final Account. Dao account. Dao; public Default. Transfer. Service(Account. Dao account. Dao) { this. account. Dao = account. Dao; } @Override public Account get. Account(Long account. Id) { return account. Dao. get(account. Id); } }
10 • Жизненный цикл бина • Создание • Внедрение зависимостей • Уничтожение
11 • Контейнер • org. springframework. beans. factory. Bean. Factory – контейнер для бинов • org. springframework. context. Application. Contex t – Bean. Factory + дополнительные возможности
12 • Типы контейнеров • Class File. System. Xml. Application. Context • Class. Path. Xml. Application. Context • Class Annotation. Config. Application. Context • Interface Web. Application. Context
13 • Создание контейнера Application. Context context = new Class. Path. Xml. Application. Context(new String[] {"services. xml", "daos. xml"});
14 • Создание веб-контейнера
15 • Конфигурация • XML • Аннотации • Java классы
16 • Конфигурация - XML
17 • Конфигурация - Аннотации @Service("transfer. Service") public class Default. Transfer. Service implements Transfer. Service { @Autowired private final Account. Dao account. Dao; @Override public Account get. Account(Long account. Id) { return account. Dao. get(account. Id); } }
18 • Конфигурация - Java @Configuration public class App. Config { @Autowired private Environment env; @Bean public Account. Dto account. Dto() { return new Jdbc. Account. Dto(); } }
19 • Aspect Oriented Programming – другой подход к модульности приложения, выделение ортогональной функциональности в «аспект»
public class Transfer. Service { • public void transfer(double amount, String from. Id, String to. Id) { Transaction. Status status =transaction. Manager. get. Transaction(); try { Account from = accounts. find. By. Id(from. Id); Account to = accounts. find. By. Id(from. Id); from. debit(amount); to. credit(amount); transaction. Manager. commit(status); }catch (Exception ex) { rollback. On. Exception(status, ex); throw ex; } // Одинаковый код, повторяющийся от метода к методу // Не связан с основной бизнес логикой }
public class Transfer. Service { • public void transfer(double amount, String from. Id, String to. Id) { Account from = accounts. find. By. Id(from. Id); Account to = accounts. find. By. Id(from. Id); from. debit(amount); to. credit(amount); }
• Data Access/Integration
23 • Web Application Layers Web Domain Model Service Data Access
24 • Data Access - Datasource public Connection get. Connection() throws SQLException{ Properties connection. Props = new Properties(); connection. Props. put("user", this. user. Name); connection. Props. put("password", this. password); Connection conn = Driver. Manager. get. Connection( "jdbc: " + this. dbms + ": //" + this. server. Name + ": " + this. port. Number + "/", connection. Props); return conn; }
25 • Data Access - Datasource
26 • Data Access. Jdbc. Template Connection con = null; Prepared. Statement pstmt = null; try { con = get. Connection(); pstmt = con. prepare. Statement( "UPDATE EMPLOYEES " + "SET CAR_NUMBER = ? " + "WHERE EMPLOYEE_NUMBER = ? "); pstmt. set. Int(1, car. No); pstmt. set. Int(2, emp. No); pstmt. execute. Update(); } finally { if (pstmt != null) pstmt. close(); }
27 • Data Access. Jdbc. Template • query. For. Int("select count(*) from t_actor") • query("select first_name, last_name from t_actor“) • update("update t_actor set = ? where id = ? ", "Banjo", 5276 L)
28 • Data Access. ORM • Hibernate • JPA • i. Batis • JDO
29 • Service. Transactions Platform. Transaction. Manager центр управления транзакциями • Hibernate. Transaction. Manager • Jpa. Transaction. Manager • Data. Source. Transaction. Manager
30 • Service. Transactions public class Transfer. Service { @Transactional public void transfer(double amount, String from. Id, String to. Id) { … } }
31 • Utils • Caching @Cacheable("books") public Book find. Book(ISBN isbn) {. . . } • Scheduling @Scheduled(cron="*/5 * * MON-FRI") public void do. Something() { // something that should execute on weekdays only }
• Web
33 • Spring MVC – Java веб фреймворк, позволяющий реализовать паттерн MVC
34 • Spring MVC Overview
35 • Dispatcher Servlet
36 • Controller @Controller public class Hello. World. Controller { @Request. Mapping("/hello. World") public String hello. World(Model model) { model. add. Attribute("message", "Hello World!"); return "hello. World"; } }
37 • View
38 • Model @Controller public class Pet. Controller { @Request. Mapping( value="pets/{pet. Id}/edit", method = Request. Method. POST) public String process. Submit( @Model. Attribute("pet") Pet pet, Binding. Result result) { if (result. has. Errors()) { return "pet. Form"; } //. . . } }
39 • Data Binding public class Pet { private Long id; private String name; private Date birth. Date; private Pet. Type type; … }
Name:
" src="https://present5.com/presentation/21861247_178049797/image-41.jpg" alt="40 • Form
" />
40 • Form
Birth Date:
41 • Развитие Spring На данный момент в Spring. Source более 14 активных проектов: http: //www. springsource. org/projects
42 • Недостатки • Большое количество классов • Сложность • ?
Spring – “стратегически важный 43 • фреймворк”
44 • Sources • http: //static. springsource. org/spring/docs/3. 1. x/ spring-framework-reference/html/ • https: //github. com/cbeams/distyles • https: //src. springframework. org/svn/spring- samples
• IKC@itransition. com @Itransition. KC