Spring通过java注解的方式进行配置annotation

原创
2017/01/02 23:58
阅读数 87

1.TestAnnotation.java

package com.huangliusong.spring.annotation;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.huangliusong.spring.annotation.controller.UserController;
import com.huangliusong.spring.annotation.respository.UserResponsitory;

public class TestAnnotation {
	@Test
	public void test1(){
		ApplicationContext ctx=new ClassPathXmlApplicationContext("bean_annotation.xml");
		TestObject to=(TestObject) ctx.getBean("testObject");
		System.out.println(to);
		
		UserController uc=(UserController) ctx.getBean("userController");
		System.out.println(uc);
		
		UserResponsitory ur=(UserResponsitory) ctx.getBean("userResponsitory");
		System.out.println(ur);
	}
}


2.TestObject.java

package com.huangliusong.spring.annotation;

import org.springframework.stereotype.Component;

@Component
public class TestObject {

}

3.UserController.java

package com.huangliusong.spring.annotation.controller;

import org.springframework.stereotype.Controller;


@Controller
public class UserController {
	public void execute(){
		System.out.println("UserController execute()...");
	}
}

4.UserResponsitory.java

package com.huangliusong.spring.annotation.respository;

public interface UserResponsitory {
	void save();
}


5.UserResponsitoryImpl.java

package com.huangliusong.spring.annotation.respository;

import org.springframework.stereotype.Repository;

//指定bean的value名
@Repository("userResponsitory")
public class UserResponsitoryImpl implements UserResponsitory{

	@Override
	public void save() {
		System.err.println("UserResponsitoryImpl >>save..");
		
	}

}

6.UserService.java

package com.huangliusong.spring.annotation.service;

import org.springframework.stereotype.Service;

@Service
public class UserService {
	public void add(){
		System.out.println("UserService add..");
	}
}

输出

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
com.huangliusong.spring.annotation.TestObject@46496daa
com.huangliusong.spring.annotation.controller.UserController@7ebed7f2
com.huangliusong.spring.annotation.respository.UserResponsitoryImpl@235391e0
 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部