javascript
java 日期注解 xml_Spring xml注解+java注解
1,xml+基于注解配置(第一步:在xml開啟注解配置)
@Component? 被表示類會(huì)被納入 spring ioc 容器進(jìn)行管理,相當(dāng)于
@Value ? ?為類注入基本類型和String屬性值
@Autowired 為類注入應(yīng)用類型屬性值;默認(rèn)按類型注入,可以通過@Qualifier("dog2")指定bean,同時(shí)也可以通過bean加入primary=true 優(yōu)先被Autowired注入
@Resource ? ? 默認(rèn)按類型注入,如果指定了name屬性,則按bean名稱注入
例:
添加配置文件beans-annotation.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
添加Dog類
@Component
public class Dog {
@Value("旺財(cái)")
private String name;
@Value("公")
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "entity.Dog [name=" + name + ", sex=" + sex + "]";
}
}
添加測(cè)試類
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans-annotation.xml");
Dog dog = (Dog) context.getBean("dog");
System.out.println(dog.toString());
}
2,java+注解配置(主流,第一步:在配置類中開啟注解掃描)
@ComponentScan("entity") 會(huì)去entity掃描@Component @Value @Autowired進(jìn)行創(chuàng)建bean或注入屬性值
注意:需要再多導(dǎo)入一個(gè)包,spring-app-5.0.14.RELEASE.jar
1)AnnotationConfigApplicationContext
@Configuration 指定該類為Spring ioc容器配置類,相當(dāng)于beans.xml文件
@Bean(name ="user") 將方法返回值納入到spring ioc容器進(jìn)行管理,相當(dāng)于
例如:
添加配置文件beans-annotation.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
添加Dog類
public class Dog {
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "entity.Dog [name=" + name + ", sex=" + sex + "]";
}
}
添加工廠類
@Configuration
@ComponentScan(basePackages = "entity")
public class BeansConfig {
@Bean
public Dog getDog(){
Dog dog = new Dog();
dog.setSex("男");
dog.setName("王二麻子");
return dog;
}
}
添加測(cè)試類
public static void main(String[] args) {
AnnotationConfigApplicationContext configApplicationContext =
new AnnotationConfigApplicationContext(BeansConfig.class);
Object dog = configApplicationContext.getBean("getDog");
System.out.println(dog);
}
總結(jié)
以上是生活随笔為你收集整理的java 日期注解 xml_Spring xml注解+java注解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab randomsample,
- 下一篇: ajax 传字符串到后台,JSON.st