Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Доброго дня.
- Использую Спринг Дата без Спринг Бут.
- Класс конфигурации выглядит так:
- @Configuration
- @EnableJpaRepositories
- public class SpringConfig {
- @Bean
- public DataSource dataSource() {
- DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
- dataSource.setUrl("jdbc:mysql://localhost:3306/kvi?useSSL=false");
- dataSource.setUsername("");
- dataSource.setPassword("");
- return dataSource;
- }
- @Bean
- public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
- LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
- entityManagerFactoryBean.setDataSource(dataSource());
- entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
- entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
- entityManagerFactoryBean.setJpaProperties(hibProperties());
- entityManagerFactoryBean.setPackagesToScan("repository", "models");
- return entityManagerFactoryBean;
- }
- private Properties hibProperties() {
- Properties jpaProperties = new Properties();
- jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
- jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");
- jpaProperties.setProperty("hibernate.connection.useUnicode", "true");
- jpaProperties.setProperty("hibernate.connection.characterEncoding", "UTF-8");
- return jpaProperties;
- }
- @Bean
- public JpaTransactionManager transactionManager() {
- JpaTransactionManager transactionManager = new JpaTransactionManager();
- transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
- return transactionManager;
- }
- }
- Это репозиторий:
- @Repository
- public interface PersonRepository extends CrudRepository<Person, Long>{
- }
- Это сервис:
- @Service
- @Transactional
- public class PersonService {
- @Autowired
- private PersonRepository personRepository;
- public Iterable<Person> findAll () {
- return personRepository.findAll();
- }
- }
- Ну и соотвественно есть ентити Person. Его приводить не буду.
- Теперь запускаем приложение из класса Main:
- @ComponentScan
- public class Main {
- public static void main(String[] args) {
- ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
- AutowireCapableBeanFactory autowireCapableBeanFactory = context.getAutowireCapableBeanFactory();
- PersonService ps = autowireCapableBeanFactory.createBean(PersonService.class);
- List <Person> pers = new ArrayList <>();
- Iterable<Person> findAll = ps.findAll();
- CollectionUtils.addAll(pers, findAll);
- for (Person p : pers) {
- System.out.println(p);
- }
- }
- }
- Все работает отлично. Но проблема в том, что каждый раз получать сервис через контекст, как это указано в коде (`PersonService ps = autowireCapableBeanFactory.createBean(PersonService.class`);), мягко говоря не удобно.
- Вопрос в том, как заставить работать Autowired, не создавая экземпляр класса сервиса из контекста?
- Заранее благодарен.
Add Comment
Please, Sign In to add comment