如何在不从上下文创建服务类实例的情况下使 Autowired 工作?我使用没有 Spring Booth 的 Spring Date。配置类:
@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 实体(我不会列出)。从主类启动:
@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);)所示,说白了就是不方便。
在注释中指定
@ComponentScan扫描的基本包@ComponentScan("com.company")。也许 Spring 只是看不到你的课程。注释
@Autowired仅适用于 bean。main只有初始化上下文并从中获取“根”bean 才有意义。并在这个 bin 和嵌入其中的 bin 中完成其余的工作。