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

Скачать презентацию Spring Dmitry Dvoynov План Core Container Data Access/Integration Скачать презентацию Spring Dmitry Dvoynov План Core Container Data Access/Integration

31896-spring.ppt

  • Количество слайдов: 46

>Spring Dmitry Dvoynov Spring Dmitry Dvoynov

>План Core Container Data Access/Integration Web  1 План Core Container Data Access/Integration Web 1

>Core Container Core Container

>Spring 3 Спринг –коллекция мощных и гибких инструментов упрощающих разработку приложений Spring 3 Спринг –коллекция мощных и гибких инструментов упрощающих разработку приложений

>public class TransferService {     public void transfer(double amount,  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,  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 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 – управление зависимостями находится не внутри объекта , IoC и DI Inversion of Control – управление зависимостями находится не внутри объекта , а – снаружи Dependency Injection – внедрение зависимостей в объект 7

>Основы Spring Bean – объект, который создается и управляется контейнером Container – приложение, отвечающее Основы Spring Bean – объект, который создается и управляется контейнером Container – приложение, отвечающее за создание и конфигурирование бинов Configuration metadata – описание конфигурации контейнера 8

>Spring Bean public class DefaultTransferService implements TransferService {    private final AccountDao 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 Жизненный цикл бина Создание Внедрение зависимостей Уничтожение 10

>Контейнер org.springframework.beans.factory.BeanFactory – контейнер для бинов org.springframework.context.ApplicationContext – BeanFactory + дополнительные возможности  11 Контейнер org.springframework.beans.factory.BeanFactory – контейнер для бинов org.springframework.context.ApplicationContext – BeanFactory + дополнительные возможности 11

>Типы контейнеров Class FileSystemXmlApplicationContext Class ClassPathXmlApplicationContext Class AnnotationConfigApplicationContext Interface WebApplicationContext  12 Типы контейнеров Class FileSystemXmlApplicationContext Class ClassPathXmlApplicationContext Class AnnotationConfigApplicationContext Interface WebApplicationContext 12

>Создание контейнера  ApplicationContext context =     new ClassPathXmlApplicationContext(new String[] { Создание контейнера ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"}); 13

>Создание веб-контейнера <servlet>     <servlet-name>dispatcher</servlet-name>     <servlet-class> Создание веб-контейнера dispatcher org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/spring/dispatcher-config.xml 1 dispatcher / 14

>Конфигурация XML Аннотации Java классы 15 Конфигурация XML Аннотации Java классы 15

>Конфигурация - XML <beans>   <bean id= Конфигурация - XML 16

>Конфигурация - Аннотации @Service( Конфигурация - Аннотации @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  Конфигурация - Java @Configuration public class AppConfig { @Autowired private Environment env; @Bean public AccountDto accountDto() { return new JdbcAccountDto(); } } 18

>Aspect Oriented Programming Aspect Oriented Programming – другой подход к модульности приложения, выделение ортогональной Aspect Oriented Programming Aspect Oriented Programming – другой подход к модульности приложения, выделение ортогональной функциональности в «аспект» 19

>public class TransferService {     public void transfer(double amount,  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,  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 Data Access/Integration

>Web Application Layers 23 Web Application Layers 23

>Data Access - Datasource 24 public Connection getConnection() throws SQLException{    Properties 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; }

" src="https://present5.com/presentacii-2/20171211\31896-spring.ppt\31896-spring_26.jpg" alt=">Data Access - Datasource 25 " /> Data Access - Datasource 25

>Data Access. JdbcTemplate  Connection con = null; PreparedStatement pstmt = null;  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( 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 Data Access. ORM Hibernate JPA iBatis JDO 28

>Service. Transactions PlatformTransactionManager центр управления транзакциями HibernateTransactionManager JpaTransactionManager DataSourceTransactionManager 29 Service. Transactions PlatformTransactionManager центр управления транзакциями HibernateTransactionManager JpaTransactionManager DataSourceTransactionManager 29

>Service. Transactions public class TransferService {     @Transactional   public Service. Transactions public class TransferService { @Transactional public void transfer(double amount, String fromId, String toId) { … } } 30

>Utils Caching  @Cacheable( 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 Web

>Spring MVC Spring MVC – Java веб фреймворк, позволяющий реализовать паттерн MVC 33 Spring MVC Spring MVC – Java веб фреймворк, позволяющий реализовать паттерн MVC 33

>Spring MVC Overview 34 Spring MVC Overview 34

>Dispatcher Servlet <web-app>      <servlet>     Dispatcher Servlet example org.springframework.web.servlet.DispatcherServlet 1 example /example/* 35

>Controller @Controller public class HelloWorldController {      @RequestMapping( 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 " /> View 37

>Model @Controller public class PetController {  @RequestMapping( value= 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;  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 Name:

Birth" /> Form Name:

Birth Date: (yyyy-mm-dd) Type:
40

>Развитие Spring На данный момент в SpringSource более 14 активных проектов: http://www.springsource.org/projects  41 Развитие Spring На данный момент в SpringSource более 14 активных проектов: http://www.springsource.org/projects 41

>Недостатки Большое количество классов Сложность ? 42 Недостатки Большое количество классов Сложность ? 42

>Spring – “стратегически важный фреймворк” 43 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 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

>IKC@itransition.com @ItransitionKC [email protected] @ItransitionKC