赞
踩
public class Tire { private int size; public Tire(int size){ this.size = size; System.out.println("tire"); } } public class Bottom { private Tire tire; public Bottom(Tire tire){ this.tire = tire; System.out.println("bottom"); } } public class Framework { private Bottom bottom; public Framework(Bottom bottom){ this.bottom = bottom; System.out.println("framework"); } } public class Main { public static void main(String[] args) { Tire tire = new Tire(20); Bottom bottom = new Bottom(tire); Framework framework = new Framework(bottom); } }
有什么:@Controller、@Service、@Repository、@Configuration、@Component
类注解作用:方便区分(看到这个注解就可知道该代码属于哪一层)
使用范围:自己的代码 + 类上
五大注解修饰的类,默认都是预加载,但我们可以设置为懒加载
使用类注解得到的Bean:哪怕我们用不同的方式去获取,得到的都是同一个对象
调用顺序:
关于Spring的扫描:在Spring项目中,当项目启动时,它会根据配置扫描特定的注解以自动注册和管理Bean
关于扫描路径:
关于Bean的命名:
@Controller public class UserController { public void doController(){ System.out.println("do Controller"); } } @SpringBootApplication public class loCTest { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(loCTest.class, args); UserController userController = context.getBean(UserController.class); userController.doController(); } }
@Data
public class UserInfo {
private String username;
private String password;
}
@Configuration public class BeanConfig { @Bean public UserInfo userInfoZ(){ UserInfo userInfo = new UserInfo(); userInfo.setUsername("zhangsan"); userInfo.setPassword("123456"); return userInfo; } @Bean public UserInfo userInfoL(){ UserInfo userInfo = new UserInfo(); userInfo.setUsername("lisi"); userInfo.setPassword("123456"); return userInfo; } }
@SpringBootApplication
public class loCTest {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(loCTest.class, args);
UserInfo userConfig = (UserInfo) context.getBean("userInfoZ");
UserInfo userConfig1 = (UserInfo) context.getBean("userInfoL");
System.out.println(userConfig == userConfig1); //结果为false
}
}
@Configuration public class BeanConfig { @Bean public UserInfo userInfoW(String nameZ){ UserInfo userInfo = new UserInfo(); userInfo.setUsername(nameZ); userInfo.setPassword("123456"); return userInfo; } @Bean public String nameW(){ return "wangwu"; } @Bean public String nameZ(){ //定义了一个叫nameZ的String类型的对象 return "zhaoliu"; } }
@SpringBootApplication
public class loCTest {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(loCTest.class, args);
UserInfo userConfigW = (UserInfo) context.getBean("userInfoW");
System.out.println(userConfigW.getUsername()); //zhaoliu
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。