1.声明bean的注解
@override 重写
@Component 表明是一个组件对象
@Repository 表明是数据访问层的类识别bean 即注解访问层bean
@Service 表示业务逻辑层
@Controller 标注控制器组件类
注入bean的注解
@Autowired 该注解可以对类成员变量,方法,即构造方法进行标注完成自动装配工作;通过@Autowired的使用消除setter和getter方法默认按照Bean类型进行装配
@Resouce
创建dao层接口及其实现类
package com.example.xuexi.dao;
public interface TestDao {
public void save();
}
package com.example.xuexi.dao;
import org.springframework.stereotype.Repository;
@Repository
public class TestDaoImpl implements TestDao{
@Override
public void save(){
System.out.println("TestDao save");
}
}
创建service层
package com.example.xuexi.service;
public interface TestService {
public void save();
}
package com.example.xuexi.service;
import com.example.xuexi.dao.TestDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestDao testDao;
@Override
public void save(){
testDao.save();
System.out.println("TestController save");
}
}
创建Controller层
package com.example.xuexi.conctroller;
import com.example.xuexi.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class TestController {
@Autowired
private TestService testService;
public void save(){
testService.save();
System.out.println("TestController save");
}
}
创建配置类
package com.example.xuexi.configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration //这是一个配置类
@ComponentScan("com.example.xuexi") //
public class ConfigConfiguration {
}
创建测试类xuexiApplication
package com.example.xuexi;
import com.example.xuexi.conctroller.TestController;
import com.example.xuexi.configuration.ConfigConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
public class XuexiApplication {
public static void main(String[] args) {
SpringApplication.run(XuexiApplication.class, args);
AnnotationConfigApplicationContext appCon = new AnnotationConfigApplicationContext(ConfigConfiguration.class);
TestController tc = appCon.getBean(TestController.class);
tc.save();
appCon.close();
}
}
项目结构