Lui*_*ano 2 java xml spring inversion-of-control
好的,这个问题会得到很多挫折......
我刚刚看到这个问题,一个人面临一些问题与spring xml beanfactory的事情.
我想明白为什么这个:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="namingStrategy">
<ref bean="namingStrategy"/>
</property>
<property name="mappingResources">
<list>
<!--<value>genericdaotest/domain/Person.hbm.xml</value>-->
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
无论如何应该比这更好:
public class BeanFactory {
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
bean.setNamingStrategy(getNamingStrategy());
bean.setMappingResources(Arrays.asList(getPerson());
bean.setHibernateProperties(new Properties() {{
setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
setProperty("hibernate.show_sql", "true")
setProperty("hibernate.hbm2ddl.auto", "create");
}});
bean.setDataSource(getDataSource());
return bean;
}
}
Run Code Online (Sandbox Code Playgroud)
它更短,更容易理解,它没有Spring怪癖,它不需要运行外部库(可能与其他人发生冲突),它是逐步调试的,它是'单元可测试的,它没有'需要反射,它可能有利于OOP,它更容易从IDE重构,它在编译时检查类型,它是Java-not xml-并且不需要在运行时解析,当它编译时你已经知道它已经在形式上是正确的(并且不会在运行时发现异常),如果需要外化某些配置参数,则使用属性文件(将包含实际配置).
而且不仅仅是一切:我不需要在我的代码中使用一个名为"BeanFactory"的庞大单例类,它负责实例化各种对象(比如与IoC原理无关的庞大而丑陋的服务定位器).
所以,问题是:
为什么我更喜欢创建一个巨大的XML而不是创建我的对象在Java中组合和聚合它们?
使用相对现代版本的Spring,你根本不会被迫使用xml.只需按如下方式注释您的课程......
@Configuration
public class BeanFactory {
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
bean.setNamingStrategy(getNamingStrategy());
bean.setMappingResources(Arrays.asList(getPerson());
bean.setHibernateProperties(new Properties() {{
setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
setProperty("hibernate.show_sql", "true")
setProperty("hibernate.hbm2ddl.auto", "create");
}});
bean.setDataSource(dataSource());
return bean;
}
@Bean
public DataSource dataSource() {
....
}
Run Code Online (Sandbox Code Playgroud)
依赖注入的真正好处在于使用bean的类.您的代码不会随着管道代码混乱,而是专注于解决业务问题.
| 归档时间: |
|
| 查看次数: |
3980 次 |
| 最近记录: |