org.springframework.beans.factory.annotation.Autowired Java Examples

The following examples show how to use org.springframework.beans.factory.annotation.Autowired. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuditingIT.java    From sdn-rx with Apache License 2.0 9 votes vote down vote up
@Test
void auditingOfModificationShouldWork(@Autowired ImmutableEntityTestRepository repository) {

	ImmutableAuditableThing thing = repository.findById(idOfExistingThing).get();
	thing = thing.withName("A new name");
	thing = repository.save(thing);

	assertThat(thing.getCreatedAt()).isEqualTo(EXISTING_THING_CREATED_AT);
	assertThat(thing.getCreatedBy()).isEqualTo(EXISTING_THING_CREATED_BY);

	assertThat(thing.getModifiedAt()).isEqualTo(DEFAULT_CREATION_AND_MODIFICATION_DATE);
	assertThat(thing.getModifiedBy()).isEqualTo("A user");

	assertThat(thing.getName()).isEqualTo("A new name");

	verifyDatabase(idOfExistingThing, thing);
}
 
Example #2
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 7 votes vote down vote up
@Test
void saveEntityWithSelfReferencesInBothDirections(@Autowired PetRepository repository) {
	Pet luna = new Pet("Luna");
	Pet daphne = new Pet("Daphne");

	luna.setFriends(singletonList(daphne));
	daphne.setFriends(singletonList(luna));

	repository.save(luna);

	try (Session session = createSession()) {
		Record record = session.run("MATCH (luna:Pet{name:'Luna'})-[:Has]->(daphne:Pet{name:'Daphne'})"
			+ "-[:Has]->(luna2:Pet{name:'Luna'})"
			+ "RETURN luna, daphne, luna2").single();

		assertThat(record.get("luna").asNode().get("name").asString()).isEqualTo("Luna");
		assertThat(record.get("daphne").asNode().get("name").asString()).isEqualTo("Daphne");
		assertThat(record.get("luna2").asNode().get("name").asString()).isEqualTo("Luna");
	}
}
 
Example #3
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void loadEntityWithBidirectionalRelationshipFromIncomingSide(@Autowired BidirectionalEndRepository repository) {

	long endId;

	try (Session session = createSession()) {
		Record record = session
			.run("CREATE (n:BidirectionalStart{name:'Ernie'})-[:CONNECTED]->(e:BidirectionalEnd{name:'Bert'}) "
				+ "RETURN e").single();

		Node endNode = record.get("e").asNode();
		endId = endNode.id();
	}

	StepVerifier.create(repository.findById(endId))
		.assertNext(entity -> {
			assertThat(entity.getStart()).isNotNull();
		})
		.verifyComplete();
}
 
Example #4
Source File: ReactiveTypeConversionIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void relatedIdsShouldBeConverted(@Autowired ConvertedIDsRepository repository) {

	ThingWithUUIDID aThing = new ThingWithUUIDID("a thing");
	aThing.setAnotherThing(new ThingWithUUIDID("Another thing"));

	List<ThingWithUUIDID> stored = new ArrayList<>();
	StepVerifier.create(repository.save(aThing))
		.recordWith(() -> stored)
		.expectNextCount(1L)
		.verifyComplete();

	ThingWithUUIDID savedThing = stored.get(0);
	assertThat(savedThing.getId()).isNotNull();
	assertThat(savedThing.getAnotherThing().getId()).isNotNull();

	StepVerifier.create(Flux.concat(repository.findById(savedThing.getId()),
		repository.findById(savedThing.getAnotherThing().getId())))
		.expectNextCount(2L)
		.verifyComplete();
}
 
Example #5
Source File: SwaggerConfig.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
/**
 * 动态产生Docket分组信息
 *
 * @return
 */
@Autowired
public void dynamicConfiguration() {
    ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();

    String systemName = "Microservice PaaS";
    ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder()
            .description("mPaas前端后端对应接口")
            .version("1.0.1")
            .license("Code Farmer Framework(iByte) Org.");

    Map<String, ModuleMappingInfo> moduleInfo = mappingHelper.getMappingInfos();
    for (Map.Entry<String, ModuleMappingInfo> entry : moduleInfo.entrySet()) {
        beanFactory.registerSingleton(entry.getKey(), new Docket(DocumentationType.SWAGGER_2)
                .groupName(entry.getKey())
                .apiInfo(apiInfoBuilder.title(systemName + NamingConstant.DOT + entry.getKey()).build())
                .select()
                .apis(genSubPackage(entry.getKey()))
                .paths(Predicates.or(PathSelectors.ant(NamingConstant.PATH_PREFIX_DATA + "/**"),
                        PathSelectors.ant(NamingConstant.PATH_PREFIX_API + "/**")))
                .build());
    }
}
 
Example #6
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void saveWithAssignedId(@Autowired ThingRepository repository) {

	assertThat(repository.count()).isEqualTo(21);

	ThingWithAssignedId thing = new ThingWithAssignedId("aaBB");
	thing.setName("That's the thing.");
	thing = repository.save(thing);

	try (Session session = createSession()) {
		Record record = session
			.run("MATCH (n:Thing) WHERE n.theId = $id RETURN n", Values.parameters("id", thing.getTheId()))
			.single();

		assertThat(record.containsKey("n")).isTrue();
		Node node = record.get("n").asNode();
		assertThat(node.get("theId").asString()).isEqualTo(thing.getTheId());
		assertThat(node.get("name").asString()).isEqualTo(thing.getName());

		assertThat(repository.count()).isEqualTo(22);
	}
}
 
Example #7
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void findWithPageable(@Autowired ReactivePersonRepository repository) {

	Sort sort = Sort.by("name");
	int page = 0;
	int limit = 1;

	StepVerifier.create(repository.findByNameStartingWith("Test", PageRequest.of(page, limit, sort)))
		.assertNext(person -> assertThat(person).isEqualTo(person1))
		.verifyComplete();


	sort = Sort.by("name");
	page = 1;
	limit = 1;

	StepVerifier.create(repository.findByNameStartingWith("Test", PageRequest.of(page, limit, sort)))
		.assertNext(person -> assertThat(person).isEqualTo(person2))
		.verifyComplete();
}
 
Example #8
Source File: ReactiveTransactionManagerMixedDatabasesTest.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void usingAnotherDatabaseExplicitTx(@Autowired ReactiveNeo4jClient neo4jClient) {

	TransactionalOperator transactionTemplate = TransactionalOperator.create(neo4jTransactionManager);

	Mono<Long> numberOfNodes = neo4jClient.query("MATCH (n) RETURN COUNT(n)").in(DATABASE_NAME).fetchAs(Long.class)
		.one()
		.as(transactionTemplate::transactional);

	StepVerifier
		.create(numberOfNodes)
		.expectErrorMatches(e ->
			e instanceof IllegalStateException && e.getMessage().equals(
				"There is already an ongoing Spring transaction for the default database, but you request 'boom'"))
		.verify();
}
 
Example #9
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void findAndInstantiateGenericRelationships(@Autowired RelationshipToAbstractClassRepository repository) {

	Inheritance.ConcreteClassA ccA = new Inheritance.ConcreteClassA("cc1", "test");
	Inheritance.ConcreteClassB ccB = new Inheritance.ConcreteClassB("cc2", 42);

	List<Inheritance.SuperBaseClass> things = new ArrayList<>();
	things.add(ccA);
	things.add(ccB);
	Inheritance.RelationshipToAbstractClass thing = new Inheritance.RelationshipToAbstractClass();
	thing.setThings(things);

	repository.save(thing);

	List<Inheritance.RelationshipToAbstractClass> all = repository.findAll();

	assertThat(all.get(0).getThings()).containsExactlyInAnyOrder(ccA, ccB);
}
 
Example #10
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void limitClauseShouldWork(@Autowired ThingRepository repository) {

	List<ThingWithAssignedId> things;

	things = repository.findTop5ByOrderByNameDesc();
	assertThat(things)
		.hasSize(5)
		.extracting(ThingWithAssignedId::getName)
		.containsExactlyInAnyOrder("name20", "name19", "name18", "name17", "name16");

	things = repository.findFirstByOrderByNameDesc();
	assertThat(things)
		.extracting(ThingWithAssignedId::getName)
		.containsExactlyInAnyOrder("name20");
}
 
Example #11
Source File: ReactiveStringlyTypeDynamicRelationshipsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test // GH-216
void shouldReadDynamicCollectionRelationships(@Autowired PersonWithRelativesRepository repository) {

	repository.findById(idOfExistingPerson)
		.as(StepVerifier::create)
		.consumeNextWith(person -> {
			assertThat(person).isNotNull();
			assertThat(person.getName()).isEqualTo("A");

			Map<String, List<Pet>> pets = person.getPets();
			assertThat(pets).containsOnlyKeys("CATS", "DOGS");
			assertThat(pets.get("CATS")).extracting(Pet::getName).containsExactlyInAnyOrder("Tom", "Garfield");
			assertThat(pets.get("DOGS")).extracting(Pet::getName).containsExactlyInAnyOrder("Benji", "Lassie");
		})
		.verifyComplete();
}
 
Example #12
Source File: ReactiveRelationshipsIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
/**
 * This stores the same instance in different relationships
 *
 * @param repository The repository to use.
 */
@Test
void shouldSaveMultipleRelationshipsOfSameInstance(@Autowired MultipleRelationshipsThingRepository repository) {

	MultipleRelationshipsThing p = new MultipleRelationshipsThing("p");
	MultipleRelationshipsThing c = new MultipleRelationshipsThing("c1");
	p.setTypeA(c);
	p.setTypeB(Collections.singletonList(c));
	p.setTypeC(Collections.singletonList(c));

	repository.save(p)
		.map(MultipleRelationshipsThing::getId)
		.flatMap(repository::findById)
		.as(StepVerifier::create)
		.assertNext(loadedThing -> {

			MultipleRelationshipsThing typeA = loadedThing.getTypeA();
			List<MultipleRelationshipsThing> typeB = loadedThing.getTypeB();
			List<MultipleRelationshipsThing> typeC = loadedThing.getTypeC();

			assertThat(typeA).isNotNull();
			assertThat(typeA).extracting(MultipleRelationshipsThing::getName).isEqualTo("c1");
			assertThat(typeB).extracting(MultipleRelationshipsThing::getName).containsExactly("c1");
			assertThat(typeC).extracting(MultipleRelationshipsThing::getName).containsExactly("c1");
		})
		.verifyComplete();

	try (Session session = driver.session()) {

		List<String> names = session.run(
			"MATCH (n:MultipleRelationshipsThing {name: 'p'}) - [r:TYPE_A|TYPE_B|TYPE_C] -> (o) RETURN r, o")
			.list(record -> {
				String type = record.get("r").asRelationship().type();
				String name = record.get("o").get("name").asString();
				return type + "_" + name;
			});
		assertThat(names).containsExactlyInAnyOrder("TYPE_A_c1", "TYPE_B_c1", "TYPE_C_c1");
	}
}
 
Example #13
Source File: ServiceInstanceDetailConsoleNotifier.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
@Autowired
  public ServiceInstanceDetailConsoleNotifier(
PasSettings appSettings,
TkService tkService) {
this.report = new ServiceInstanceDetailCsvReport(appSettings);
this.util = new TkServiceUtil(tkService);
  }
 
Example #14
Source File: LoadingBay.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Autowired
public LoadingBay(HiveTableAction hiveTableAction, Function<HiveRoad, LanderMonitor> monitorFactory) {
  this.hiveTableAction = hiveTableAction;
  this.monitorFactory = monitorFactory;

  monitors = new HashMap<>();
}
 
Example #15
Source File: SpringJUnitJupiterConstructorInjectionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
SpringJUnitJupiterConstructorInjectionTests(ApplicationContext applicationContext, @Autowired Person dilbert,
		@Autowired Dog dog, @Value("${enigma}") Integer enigma, TestInfo testInfo) {

	this.applicationContext = applicationContext;
	this.dilbert = dilbert;
	this.dog = dog;
	this.enigma = enigma;
	this.testInfo = testInfo;
}
 
Example #16
Source File: ReactiveStringlyTypeDynamicRelationshipsIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test // GH-216
void shouldWriteDynamicCollectionRelationships(@Autowired PersonWithRelativesRepository repository) {

	PersonWithStringlyTypedRelatives newPerson = new PersonWithStringlyTypedRelatives("Test");
	Map<String, List<Pet>> pets = newPerson.getPets();

	List<Pet> monsters = pets.computeIfAbsent("MONSTERS", s -> new ArrayList<>());
	monsters.add(new Pet("Godzilla"));
	monsters.add(new Pet("King Kong"));

	List<Pet> fish = pets.computeIfAbsent("FISH", s -> new ArrayList<>());
	fish.add(new Pet("Nemo"));

	List<PersonWithStringlyTypedRelatives> recorded = new ArrayList<>();
	repository.save(newPerson)
		.as(StepVerifier::create)
		.recordWith(() -> recorded)
		.consumeNextWith(person -> {
			Map<String, List<Pet>> writtenPets = person.getPets();
			assertThat(writtenPets).containsOnlyKeys("MONSTERS", "FISH");
		})
		.verifyComplete();

	try (Transaction transaction = driver.session().beginTransaction()) {
		long numberOfRelations = transaction.run(""
			+ "MATCH (t:" + labelOfTestSubject + ") WHERE id(t) = $id "
			+ "RETURN size((t)-->(:Pet))"
			+ " as numberOfRelations", Values.parameters("id", recorded.get(0).getId()))
			.single().get("numberOfRelations").asLong();
		assertThat(numberOfRelations).isEqualTo(3L);
	}
}
 
Example #17
Source File: DatabaseCreator.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
@Autowired
public DatabaseCreator(
	DatabaseClient client,
	ResourceLoader resourceLoader,
	DbmsSettings settings,
	ApplicationEventPublisher publisher) {
	this.client = client;
	this.resourceLoader = resourceLoader;
	this.settings = settings;
	this.publisher = publisher;
}
 
Example #18
Source File: HealthAutoConfiguration.java    From mykit-delay with Apache License 2.0 5 votes vote down vote up
@Bean
@Autowired(required = false)
@ConditionalOnMissingBean
public HealthIndicator jikexiuHealthIndicator(RedisQueue redisQueue, RedisQueueProperties properties) {
    CompositeHealthIndicator compositeHealthIndicator = new  CompositeHealthIndicator(healthAggregator);
    Map<String, LeaderManager> leaderManagerMap = AppEnvContext.getCtx().getBeansOfType(LeaderManager.class);
    LeaderManager manager = null;
    if (leaderManagerMap != null && !leaderManagerMap.isEmpty()) {
        manager = AppEnvContext.getCtx().getBean(SimpleLeaderManager.class);
    }

    compositeHealthIndicator.addHealthIndicator(Constants.HEALTH_INDICATOR_NAME, new QueueHealthIndicator(redisQueue, manager, properties));
    return compositeHealthIndicator;
}
 
Example #19
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void loadOptionalPersonWithAllConstructorWithSpelParameters(@Autowired PersonRepository repository) {

	Optional<PersonWithAllConstructor> person = repository
		.getOptionalPersonViaQuery(TEST_PERSON1_NAME.substring(0, 2), TEST_PERSON1_NAME.substring(2));
	assertThat(person).isPresent();
	assertThat(person.get().getName()).isEqualTo(TEST_PERSON1_NAME);
}
 
Example #20
Source File: UsageTask.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
@Autowired
public UsageTask(
        UsageService service,
        UsageCache cache,
        ObjectMapper mapper) {
    this.service = service;
    this.cache = cache;
    this.mapper = mapper;
}
 
Example #21
Source File: JdbcPetRepositoryImpl.java    From spring-graalvm-native with Apache License 2.0 5 votes vote down vote up
@Autowired
public JdbcPetRepositoryImpl(DataSource dataSource, OwnerRepository ownerRepository,
        VisitRepository visitRepository) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

    this.insertPet = new SimpleJdbcInsert(dataSource).withTableName("pets").usingGeneratedKeyColumns("id");

    this.ownerRepository = ownerRepository;
    this.visitRepository = visitRepository;
}
 
Example #22
Source File: IdGeneratorsIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void idGenerationWithNewEntityShouldWork(@Autowired ThingWithGeneratedIdRepository repository) {

	ThingWithGeneratedId t = new ThingWithGeneratedId("Foobar");
	t.setName("Foobar");
	t = repository.save(t);
	assertThat(t.getTheId())
		.isNotBlank()
		.matches("thingWithGeneratedId-\\d+");

	verifyDatabase(t.getTheId(), t.getName());
}
 
Example #23
Source File: CometCollectorConfig.java    From Milkomeda with MIT License 5 votes vote down vote up
@Autowired
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public void configResponseBodyAdvice(RequestMappingHandlerAdapter adapter, HandlerExceptionResolver handlerExceptionResolver) {
    if (!props.isEnableTag()) {
        return;
    }
    CometCollectorResponseBodyAdvice collectorResponseBodyAdvice = cometResponseBodyAdvice();
    // 动态添加到响应处理
    SpringMvcPolyfill.addDynamicResponseBodyAdvice(adapter.getReturnValueHandlers(), handlerExceptionResolver, collectorResponseBodyAdvice);
}
 
Example #24
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void findByLessThanEqual(@Autowired PersonRepository repository) {

	List<PersonWithAllConstructor> persons = repository.findAllByPersonNumberIsLessThanEqual(2L);
	assertThat(persons)
		.containsExactlyInAnyOrder(person1, person2);
}
 
Example #25
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void findEntityWithSelfReferencesInBothDirections(@Autowired PetRepository repository) {
	long petId;
	try (Session session = createSession()) {
		petId = session.run("CREATE (luna:Pet{name:'Luna'})-[:Has]->(daphne:Pet{name:'Daphne'})"
			+ "-[:Has]->(luna2:Pet{name:'Luna'})"
			+ "RETURN id(luna) as id").single().get("id").asLong();
	}
	Pet loadedPet = repository.findById(petId).get();

	assertThat(loadedPet.getFriends().get(0).getName()).isEqualTo("Daphne");
	assertThat(loadedPet.getFriends().get(0).getFriends().get(0).getName()).isEqualTo("Luna");

}
 
Example #26
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void findByConvertedCustomTypeWithSpELPropertyAccessQuery(@Autowired EntityWithCustomTypePropertyRepository repository) {
	try (Session session = createSession()) {
		session.run("CREATE (:CustomTypes{customType:'XYZ'})");
	}

	StepVerifier.create(repository.findByCustomTypeCustomSpELPropertyAccessQuery(ThingWithCustomTypes.CustomType.of("XYZ")))
		.expectNextCount(1)
		.verifyComplete();
}
 
Example #27
Source File: DynamicLabelsIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void shouldWriteDynamicLabels(@Autowired Neo4jTemplate template) {

	SimpleDynamicLabelsWithBusinessId entity = new SimpleDynamicLabelsWithBusinessId();
	entity.id = UUID.randomUUID().toString();
	entity.moreLabels = new HashSet<>();
	entity.moreLabels.add("A");
	entity.moreLabels.add("B");
	entity.moreLabels.add("C");
	template.save(entity);
	List<String> labels = getLabels(Cypher.anyNode("n").property("id").isEqualTo(parameter("id")), entity.id);
	assertThat(labels).containsExactlyInAnyOrder("SimpleDynamicLabelsWithBusinessId", "A", "B", "C");
}
 
Example #28
Source File: ArticleService.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
@Autowired
public ArticleService(ArticleDao articleDao, RedisService redisService,
                      UserServiceRpc userServiceRpc,CategoryDao categoryDao) {
	this.articleDao = articleDao;
	this.categoryDao = categoryDao;
	this.redisService = redisService;
	this.userServiceRpc = userServiceRpc;
}
 
Example #29
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void saveWithConvertedId(@Autowired EntityWithConvertedIdRepository repository) {
	EntityWithConvertedId entity = new EntityWithConvertedId();
	entity.setIdentifyingEnum(EntityWithConvertedId.IdentifyingEnum.A);
	repository.save(entity).block();

	try (Session session = createSession()) {
		Record node = session.run("MATCH (e:EntityWithConvertedId) return e").next();
		assertThat(node.get("e").get("identifyingEnum").asString()).isEqualTo("A");
	}
}
 
Example #30
Source File: ReactiveStringlyTypeDynamicRelationshipsIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void shouldWriteDynamicRelationships(@Autowired PersonWithRelativesRepository repository) {

	PersonWithStringlyTypedRelatives newPerson = new PersonWithStringlyTypedRelatives("Test");
	Person d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R1");
	newPerson.getRelatives().put("RELATIVE_1", d);
	d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R2");
	newPerson.getRelatives().put("RELATIVE_2", d);

	List<PersonWithStringlyTypedRelatives> recorded = new ArrayList<>();
	repository.save(newPerson)
		.as(StepVerifier::create)
		.recordWith(() -> recorded)
		.consumeNextWith(personWithRelatives -> {
			Map<String, Person> relatives = personWithRelatives.getRelatives();
			assertThat(relatives).containsOnlyKeys("RELATIVE_1", "RELATIVE_2");
		})
		.verifyComplete();

	try (Transaction transaction = driver.session().beginTransaction()) {
		long numberOfRelations = transaction.run(""
				+ "MATCH (t:" + labelOfTestSubject + ") WHERE id(t) = $id "
				+ "RETURN size((t)-->(:Person))"
				+ " as numberOfRelations",
			Values.parameters("id", recorded.get(0).getId()))
			.single().get("numberOfRelations").asLong();
		assertThat(numberOfRelations).isEqualTo(2L);
	}
}