Spring框架的搭建(一)
在上一篇完成了Spring基本框架的搭建,我们开始Spring项目的构建。
一、使用Maven导入所需要的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
二、创建接口和接口的实现类
public interface OneInterface {
public String inter(String name);
}
public class OneInterfaceImp implements OneInterface{
@Override
public String inter(String name) {
return name;
}
}
三、Spring配置文件在搭建框架时自动创建,可以在任意位置
Spring的配置文件中配置service
bean的配置:
1、在xml文件中配置
id:该bean的唯一标识符
class:该bean的具体实现类
<bean id="oneinterface" class="Interface.OneInterfaceImp"></bean>
2、使用注解的方式
(1)在实现类上方使用@Component注解
他的ID为实现类类名首字母小写,例:
@Component
public class OneInterfaceImp implements OneInterface{
@Override
public String inter(String name) {
return name;
}
}
这个Bean的id为oneInterfaceimp。
(2)
在Spring配置文件中声明<context:component-scan base-package="Interface" />
指定Spring解析的对应包的注解
在实现类上方使用@Configuration注解指定这个类为配置文件类
在方法名上方使用@Bean注解
该bean的id为方法名。
@Bean(name=“xxx”) 指定该Bean的id为xxx。
例:
@Configuration
public class OneInterfaceImp implements OneInterface{
@Override
@Bean(name="inters")
public String inter(String name) {
return name;
}
}
该bean的id为inters。
四、bean的使用
用ClassPathXmlApplicationContext获取Spring配置文件,
用ClassPathXmlApplicationContext中的getbean(“Bean的id”)获取bean,获取时,获得的时Object对象需要强转为响应Bean的接口类对象。
ClassPathXmlApplicationContext `cxt = new ClassPathXmlApplicationContext("spring-config.xml");
OneInterface oneInterface = (OneInterface)cxt.getBean("oneInterfaceImp");
System.out.println(oneInterface.inter("Interface"));
如上:我们就实现了一个Bean的使用。