java_spring_使用注解装配bean

1. 创建类

servicedaomodel等。

2. 添加注解

用的注解有:

@Service 定义一个service

@Controller 定义一个controller

告诉spring扫描这个类为一个controller。(不需要派生自controller了)

@Repository 定义一个Dao

@Component 效于上面三个,不推荐使用

@Autowired 实现Bean的依赖注入

 

@Repository

public class UserDao {

public void save(){

System.out.println("save");

}

}

@Service

public class UserService {

@Autowired

UserDao userdao;

public void save(){

userdao.save();

}

}

 

3. spring的配置文件中扫包:

<context:component-scan base-package="com.glodon.service"></context:component-scan>

<context:component-scan base-package="com.glodon.dao"></context:component-scan>

<context:component-scan base-package="com.glodon.model"></context:component-scan>

 

4. 测试

写一个测试类:

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"classpath:applicationContext.xml"})

public class TestUserService {

@Autowired

private UserService userService;

@Test

public void hander(){

userService.save();

}

}

 

5. 完善

因为是一个web工程,因此在添加springMVC的配置文件后,配置扫描web目录。

web目录下添加controller类及controller注解。

就可以直接使用页面测试了,而不是上面的测试方法。

注:web项目需要先引入spring的配置文件:

web.xml中添加配置:

<!-- 加载spring的配置文件 -->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext.xml</param-value>

</context-param>

<!-- 监听application的上下文,放入application对象中 -->

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值