Guest User

Untitled

a guest
Oct 30th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.00 KB | None | 0 0
  1. Доброго дня.
  2. Использую Спринг Дата без Спринг Бут.
  3.  
  4. Класс конфигурации выглядит так:
  5.  
  6.  
  7.  
  8. @Configuration
  9. @EnableJpaRepositories
  10. public class SpringConfig {
  11.  
  12. @Bean
  13. public DataSource dataSource() {
  14. DriverManagerDataSource dataSource = new DriverManagerDataSource();
  15.  
  16. dataSource.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
  17. dataSource.setUrl("jdbc:mysql://localhost:3306/kvi?useSSL=false");
  18. dataSource.setUsername("");
  19. dataSource.setPassword("");
  20. return dataSource;
  21. }
  22.  
  23. @Bean
  24. public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
  25.  
  26. LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
  27. entityManagerFactoryBean.setDataSource(dataSource());
  28. entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
  29. entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
  30.  
  31. entityManagerFactoryBean.setJpaProperties(hibProperties());
  32. entityManagerFactoryBean.setPackagesToScan("repository", "models");
  33.  
  34. return entityManagerFactoryBean;
  35.  
  36. }
  37.  
  38. private Properties hibProperties() {
  39. Properties jpaProperties = new Properties();
  40. jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
  41. jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");
  42.  
  43. jpaProperties.setProperty("hibernate.connection.useUnicode", "true");
  44. jpaProperties.setProperty("hibernate.connection.characterEncoding", "UTF-8");
  45. return jpaProperties;
  46. }
  47.  
  48.  
  49. @Bean
  50. public JpaTransactionManager transactionManager() {
  51. JpaTransactionManager transactionManager = new JpaTransactionManager();
  52. transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
  53. return transactionManager;
  54. }
  55.  
  56. }
  57.  
  58. Это репозиторий:
  59.  
  60. @Repository
  61. public interface PersonRepository extends CrudRepository<Person, Long>{
  62. }
  63.  
  64. Это сервис:
  65. @Service
  66. @Transactional
  67. public class PersonService {
  68.  
  69. @Autowired
  70. private PersonRepository personRepository;
  71.  
  72. public Iterable<Person> findAll () {
  73. return personRepository.findAll();
  74. }
  75. }
  76.  
  77. Ну и соотвественно есть ентити Person. Его приводить не буду.
  78. Теперь запускаем приложение из класса Main:
  79.  
  80. @ComponentScan
  81. public class Main {
  82. public static void main(String[] args) {
  83.  
  84. ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
  85. AutowireCapableBeanFactory autowireCapableBeanFactory = context.getAutowireCapableBeanFactory();
  86. PersonService ps = autowireCapableBeanFactory.createBean(PersonService.class);
  87.  
  88. List <Person> pers = new ArrayList <>();
  89. Iterable<Person> findAll = ps.findAll();
  90. CollectionUtils.addAll(pers, findAll);
  91. for (Person p : pers) {
  92. System.out.println(p);
  93. }
  94.  
  95. }
  96.  
  97. }
  98.  
  99. Все работает отлично. Но проблема в том, что каждый раз получать сервис через контекст, как это указано в коде (`PersonService ps = autowireCapableBeanFactory.createBean(PersonService.class`);), мягко говоря не удобно.
  100.  
  101. Вопрос в том, как заставить работать Autowired, не создавая экземпляр класса сервиса из контекста?
  102. Заранее благодарен.
Add Comment
Please, Sign In to add comment