Spring Dmitry Dvoynov План Core Container Data Access/Integration













![Создание контейнера ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { Создание контейнера ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {](https://present5.com/presentacii-2/20171211\31896-spring.ppt\31896-spring_14.jpg)
























Birth" src="https://present5.com/presentacii-2/20171211\31896-spring.ppt\31896-spring_41.jpg" alt="Form
Birth" />





31896-spring.ppt
- Количество слайдов: 46
Spring Dmitry Dvoynov
План Core Container Data Access/Integration Web 1
Core Container
Spring 3 Спринг –коллекция мощных и гибких инструментов упрощающих разработку приложений
public class TransferService { public void transfer(double amount, String fromId, String toId) { // TransferService зависит от accountDao // где должен быть объявлен accountDao? Account from = accountDao.findById(fromId); Account to = aaccountDao.findById(fromId); from.debit(amount); to.credit(amount); accountDao.save(from); accountDao.save(to); } }
public class TransferService { public void transfer(double amount, String fromId, String toId) { AccountDao accountDao = new JdbcAccountDao(...); // создание внутри метода? //TransferService управляет созданием accounts //TransferService знает о реализации JdbcAccountDao //TransferService сложно протестировать Account from = accountDao.findById(fromId); Account to = accountDao.findById(fromId); from.debit(amount); to.credit(amount); accountDao.save(from); accountDao.save(to); } }
public class TransferService { private final AccountDao accountDao; public TransferService(AccountDao accountDao) { this.accountDao = accountDao; } public void transfer(double amount, String fromId, String toId) { //Реализация метода осталась простой, хорошо тестируемой Account from = accountDao.findById(fromId); Account to = accountDao.findById(fromId); from.debit(amount); to.credit(amount); accountDao.save(from); accountDao.save(to); } }
IoC и DI Inversion of Control – управление зависимостями находится не внутри объекта , а – снаружи Dependency Injection – внедрение зависимостей в объект 7
Основы Spring Bean – объект, который создается и управляется контейнером Container – приложение, отвечающее за создание и конфигурирование бинов Configuration metadata – описание конфигурации контейнера 8
Spring Bean public class DefaultTransferService implements TransferService { private final AccountDao accountDao; public DefaultTransferService(AccountDao accountDao) { this.accountDao = accountDao; } @Override public Account getAccount(Long accountId) { return accountDao.get(accountId); } } 9
Жизненный цикл бина Создание Внедрение зависимостей Уничтожение 10
Контейнер org.springframework.beans.factory.BeanFactory – контейнер для бинов org.springframework.context.ApplicationContext – BeanFactory + дополнительные возможности 11
Типы контейнеров Class FileSystemXmlApplicationContext Class ClassPathXmlApplicationContext Class AnnotationConfigApplicationContext Interface WebApplicationContext 12
Создание контейнера ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"}); 13
Создание веб-контейнера
Конфигурация XML Аннотации Java классы 15
Конфигурация - XML
Конфигурация - Аннотации @Service("transferService") public class DefaultTransferService implements TransferService { @Autowired private final AccountDao accountDao; @Override public Account getAccount(Long accountId) { return accountDao.get(accountId); } } 17
Конфигурация - Java @Configuration public class AppConfig { @Autowired private Environment env; @Bean public AccountDto accountDto() { return new JdbcAccountDto(); } } 18
Aspect Oriented Programming Aspect Oriented Programming – другой подход к модульности приложения, выделение ортогональной функциональности в «аспект» 19
public class TransferService { public void transfer(double amount, String fromId, String toId) { TransactionStatus status =transactionManager.getTransaction(); try { Account from = accounts.findById(fromId); Account to = accounts.findById(fromId); from.debit(amount); to.credit(amount); transactionManager.commit(status); }catch (Exception ex) { rollbackOnException(status, ex); throw ex; } // Одинаковый код, повторяющийся от метода к методу // Не связан с основной бизнес логикой }
public class TransferService { public void transfer(double amount, String fromId, String toId) { Account from = accounts.findById(fromId); Account to = accounts.findById(fromId); from.debit(amount); to.credit(amount); }
Data Access/Integration
Web Application Layers 23
Data Access - Datasource 24 public Connection getConnection() throws SQLException{ Properties connectionProps = new Properties(); connectionProps.put("user", this.userName); connectionProps.put("password", this.password); Connection conn = DriverManager.getConnection( "jdbc:" + this.dbms + "://" + this.serverName + ":" + this.portNumber + "/", connectionProps); return conn; }
Data Access. JdbcTemplate Connection con = null; PreparedStatement pstmt = null; try { con = getConnection(); pstmt = con.prepareStatement( "UPDATE EMPLOYEES " + "SET CAR_NUMBER = ? " + "WHERE EMPLOYEE_NUMBER = ?"); pstmt.setInt(1, carNo); pstmt.setInt(2, empNo); pstmt.executeUpdate(); } finally { if (pstmt != null) pstmt.close(); } 26
Data Access. JdbcTemplate queryForInt("select count(*) from t_actor") query("select first_name, last_name from t_actor“) update("update t_actor set = ? where id = ?","Banjo", 5276L) 27
Data Access. ORM Hibernate JPA iBatis JDO 28
Service. Transactions PlatformTransactionManager центр управления транзакциями HibernateTransactionManager JpaTransactionManager DataSourceTransactionManager 29
Service. Transactions public class TransferService { @Transactional public void transfer(double amount, String fromId, String toId) { … } }
Utils Caching @Cacheable("books") public Book findBook(ISBN isbn) {...} Scheduling @Scheduled(cron="*/5 * * * * MON-FRI") public void doSomething() { // something that should execute on weekdays only } 31
Web
Spring MVC Spring MVC – Java веб фреймворк, позволяющий реализовать паттерн MVC 33
Spring MVC Overview 34
Dispatcher Servlet
Controller @Controller public class HelloWorldController { @RequestMapping("/helloWorld") public String helloWorld(Model model) { model.addAttribute("message", "Hello World!"); return "helloWorld"; } } 36
" src="https://present5.com/presentacii-2/20171211\31896-spring.ppt\31896-spring_38.jpg" alt=">View
Model @Controller public class PetController { @RequestMapping( value="pets/{petId}/edit", method = RequestMethod.POST) public String processSubmit( @ModelAttribute("pet") Pet pet, BindingResult result) { if (result.hasErrors()) { return "petForm"; } // ... } } 38
Data Binding public class Pet { private Long id; private String name; private Date birthDate; private PetType type; … } 39
Name:
Birth" src="https://present5.com/presentacii-2/20171211\31896-spring.ppt\31896-spring_41.jpg" alt=">Form
Birth" />
Form
Birth Date:
Развитие Spring На данный момент в SpringSource более 14 активных проектов: http://www.springsource.org/projects 41
Недостатки Большое количество классов Сложность ? 42
Spring – “стратегически важный фреймворк” 43
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 44
[email protected] @ItransitionKC

