ApplicationContext app = new ClassPathXmlApplicationContext("核心配置文件名.xml");
ApplicationContext app = new AnnotationConfigApplicationContext(核心配置类.class);
Object bean = app.getBean("唯一标识");//需要强转
对应类型 对象名= app.getBean("唯一标识", javabean.class类型)//无需强转
无参构造方法实例化:让Spring调用bean的无参构造,生成bean实例对象
<bean id="accountDao" class="com.Xxxx.dao.impl.AccountDaoImpl"></bean>
工厂静态方法实例化:让Spring调用一个工厂类的静态方法,得到一个bean实例对象,假设在com.Xxxx包下创建factory(工厂包),创建一个StaticFactory工厂类
public class StaticFactory{
public static AccountDao createAccountDao(){
return new AccountDaoImpl();
}
}
核心配置文件:
<bean id="accountDao" class="com.Xxxx.factory.StaticFactory"
factory-method="createAccountDao"></bean>
<!-- 先配置工厂 -->
<bean id="instanceFactory" class="com.Xxxx.factory.InstanceFactory"></bean>
<!-- 再配置AccountDao -->
<bean id="accountDao" factory-bean="instanceFactory" factory-method="createAccountDao"></bean>
<bean id="" class="">
<property name="属性名" value="属性值"></property>
<property name="属性名" ref="bean的id"></property>
</bean>
<bean id="" class="">
<constructor-arg name="构造参数名称" value="构造参数的值"></constructor-arg>
<constructor-arg name="构造参数名称" ref="bean的id"></constructor-arg>
</bean>
jdbc.driver=com.mysql.jdbc.Driver //驱动
jdbc.url=jdbc:mysql:///spring //数据库名
jdbc.username=root //数据库账号
jdbc.password=root //数据库密码
<context:property-placeholder location="classpath:jdbc.properties"/>
需要导入Context命名空间<beans
xmlns:名称空间="http://www.springframework.org/schema/名称空间"
xsi:scehmaLocation="
http://www.springframework.org/schema/名称空间
http://www.springframework.org/schema/名称空间/spring-名称空间.xsd">
</beans>
读取jdbc.properties中的文件使用${配置文件中的key获取对应的值}
在大型项目开发中,如果把所有的配置都写在一个配置文件applicationContext.xml中,会导致:
Spring提供了分模块配置的方式,即:每个模块提供一个配置文件,在核心配置文件中引入模块配置:
<import resource="applicationContext-xx.xml"/>
<import resource="applicationContext-yy.xml"/>
以上例环境为例,进行注解开发
编写类
@Component:类级别的一个注解,用于声明一个bean,使用不多
value属性:bean的唯一标识。如果不配置,默认以首字母小写的变量名为id
@Controller, @Service, @Repository,作用和@Component完全一样,但更加的语义化,使用更多
@Controller:用于web层的bean
@Service:用于Service层的bean
@Reposiroty:用于dao层的bean
绝大多数情况下,只要使用@Autowired注解注入即可
注解注入时,不需要set方法了
核心配置文件
运行测试
1. 在pom.xml文件中增加依赖:spring-test 和 junit
2. 修改单元测试类
1. 在单元测试类上增加注解:@RunWith(SpringJunit4ClassRunner.class)
目的:使用Spring的单元测试运行器,替换Junit原生的运行器
2. 在单元测试类上增加注解:@ContextConfiguration()
目的:指定配置文件或配置类
因篇幅问题不能全部显示,请点此查看更多更全内容