您的位置:首页 > 编程语言 > Java开发

采用Spring管理Bean和依赖注入

2014-06-17 12:39 615 查看
1.实例化spring容器 和 从容器获取Bean目标实例化Spring容器常用的两种办法:办法一:在类途径下寻觅配置文件来实例化容器 [引荐运用]ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});办法二:在文件体系途径下寻觅配置文件来实例化容器 [这种办法能够在开发期间运用]ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[]{“d:\\beans.xml“});Spring的配置文件能够指定多个,能够经过String数组传入。
当spring容器启动后,由于spring容器能够办理bean目标的创立,毁掉等生命周期,所以咱们只需从容器直接获取Bean目标就行,而不必编写一句代码来创立bean目标。从容器获取bean目标的代码如下:ApplicationContext ctx = new ClassPathXmlApplicationContext(“beans.xml”);OrderService service = (OrderService)ctx.getBean("personService");
<?xml version="1.0" encoding="UTF-8"?><beans xmlns=" http://www.metabase.cn/schema/beans"<beans xmlns=" http://www.jinanwuliangye.com/schema/beans"<beans xmlns=" http://www.tongxinglong.com/schema/beans"<beans xmlns=" http://www.qclchina.com/schema/beans"<beans xmlns=" http://www.vipfuxin.com//schema/beans"xsi:schemaLocation=" http://www.minnan888.net/schema/mvc/spring-mvc-3.2.xsd http://www.lcsyt.com/schema/mvc/spring-mvc-3.2.xsd http://lf.yunnanw.cn//schema/mvc/spring-mvc-3.2.xsd http://www.ceocbs.com/schema/mvc/spring-mvc-3.2.xsd http://www.yzbljp.com/schema/mvc/spring-mvc-3.2.xsd http://www.hyyfscl.com//schema/mvc/spring-mvc-3.2.xsdhttp://www.shoudashou.com//schema/mvc/spring-mvc-3.2.xsdhttp://www.shuoma.com.cn//schema/mvc/spring-mvc-3.2.xsd "> <!-- @Controller, @Service, @Configuration, etc. --> <!-- 启动Spring注解功能 --> <context:component-scan base-package="com.yeeeueyf.controller" />
<mvc:annotation-driven /><mvc:default-servlet-handler />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring 配置文件 Bean