Spring框架的搭建(二)

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的使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值